#[SOLVED] Complex class creator - Failed to serialize result: Object of type xxx is not JSON

1 messages · Page 1 of 1 (latest)

glacial sun
#

Hi all

I've tried to do something like this (https://docs.dagger.io/api/constructor/#simple-constructor) i.e. having a class constructor where I'll initialize a custom class and it didn't work.

So far I've understood, my own class Environment is not serializable but, yes, I've well create a to_dict() or__dict__() method as suggested by IA tools.

My Main class looks like this (simplified):

from .core.environment import Environment

@object_type
class Src:
    env: Environment

     @classmethod
    async def create(cls):
        # [...]
        env: Environment = cls.__load_environment()
        # [...]
        return cls(env=env)

My Environment class is there to store all my attributes. Nothing special there.

Looks like this:

class Environment:

    def __init__(self, project_type="", base_image="", verbose=False):
        self.base_image: str = project_type
        self.project_type: str = base_image
        self.verbose: bool = verbose

    def to_dict(self):
        return {
            "project_type": self.project_type,
            "base_image": self.base_image,
            "verbose": self.verbose,
        }

I've the feeling something has to be done in the Dagger CI Python SDK to allow the constructor to serialize/deserialize my class but not sure.

Every Dagger module has a constructor. The default one is generated automatically and has no arguments.

wet tiger
#

The problem is Environment isn't exposed as a Dagger type, so you either need to do that or make the env property in Src private. Try this:

@dagger.object_type
class Environment:
    project_type: str = dagger.field(default="")
    base_image: str = dagger.field(default="")
    verbose: bool = dagger.field(default=False)

Reminder that dagger.object_type wraps dataclass, so no need for that constructor and to_dict.

#

Should also be able to do something like this:

@dagger.object_type
class Src:
    env: Environment = dagger.field(default=_load_environment)

So no need for custom create. This assumes _load_environment is a function, not a Src method, so adjust accordingly. The main point is that the default in dagger.field can be a callable (without arguments) that returns the default value.

glacial sun
#

Absolutely brilliant! I was stuck on this question for three hours before I thought I should ask for help.

Thank you!!!