Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduction of a generic schema used to type load and loads #267

Open
Vince-LD opened this issue May 28, 2024 · 2 comments
Open

Introduction of a generic schema used to type load and loads #267

Vince-LD opened this issue May 28, 2024 · 2 comments

Comments

@Vince-LD
Copy link

Vince-LD commented May 28, 2024

Hello,

This week, I've started to use marshmallow and marshmallow_dataclass at work for the first time and it's absolutely great. However, I was wondering if there was a reason not to use a generic schema to keep track of the wrapped dataclass when using class_schema factory.

The basic idea is pretty simple:

# have a custom schema class that is used only for type checking
class DataclassSchema(Generic[_T]):
    if TYPE_CHECKING:
        # use some overloading here to chose between the two result types
        def load(...) -> Union[_T, List[_T]]: ...

# update `class_schema` signature
def class_schema(clazz: Typ[_T], ...) -> Type[DataclassSchema[_T]]: ...

Then we can create a dataclass and the corresponding schema:

@dataclass
class Test:
    a : int
    b : str

# The types can actually be inferred by Pyright
schema: DataclassSchema[Test] = class_schema(Test)()
data: Test = schema.load({"a": 0, "b": "hellow world :)")

I have created a first implementation of this proposal in this fork. I am not familiar with mypy (I use Pyright through Pylance) and really advanced typing so I don't know if this is the best way to achieve my goal. If this subject interests you I'd be glad to contribute :)

Cheers,
Vincent

Edit: Sorry for the tag....

@ddorian
Copy link

ddorian commented Jun 1, 2024

Like https://github.com/daniil-berg/marshmallow-generic ?

@Vince-LD
Copy link
Author

Vince-LD commented Jun 1, 2024

Yes, I'm proposing something similar. Actually, my first implementation works really well in real conditions (used it at work this week). I'm going to try another implentation by using marshmallow-generic but it would still require to modify the signature of marshmallow_dataclass.class_schema to use this generic Schema and a dataclass TypeVar instead of type and Schema.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants