lovasoa / marshmallow_dataclass

Automatic generation of marshmallow schemas from dataclasses.
https://lovasoa.github.io/marshmallow_dataclass/html/marshmallow_dataclass.html
MIT License
458 stars 78 forks source link

Using NewType raises TypeError #217

Closed EloiZalczer closed 2 years ago

EloiZalczer commented 2 years ago

When running the example code from the NewType docstring, I get the following exception:

import marshmallow.validate
IPv4 = NewType('IPv4', str, validate=marshmallow.validate.Regexp(r'^([0-9]{1,3}\\.){3}[0-9]{1,3}$'))
@dataclass
class MyIps:
   ips: List[IPv4]
MyIps.Schema().load({"ips": ["0.0.0.0", "grumble grumble"]})

TypeError: IPv4 is not a dataclass and cannot be turned into one.

The issue seems to happen in typing_inspect.py at line 287, in function is_new_type. For versions prior to Python 3.10.0, the check is the following:

return (tp is NewType or
       (getattr(tp, '__supertype__', None) is not None and
       getattr(tp, '__qualname__', '') == 'NewType.<locals>.new_type' and
       tp.__module__ in ('typing', 'typing_extensions')))

However, in the case of new types created via marshmallowdataclass, the \_module__ is set to 'marshmallow_dataclass'. Therefore, the new type is not recognized as such and marshmallow_dataclass treats it as a nested field.

I'm using Python 3.8 and marshmallow-dataclass==8.5.8

dairiki commented 2 years ago

I believe this is a duplicate of #206. If so, it is fixed in the master branch but the fix has not yet made it into a release. See PRs #207 and #211

A workaround is to pin typing-inspect<0.8.0. I will see if I can generate a new release of marshmallow-dataclass.

dairiki commented 2 years ago

Fixed in marshmallow_dataclass==8.5.9

EloiZalczer commented 2 years ago

Thanks for the release ! Sorry about the duplicate.