dataclasses-json
dataclasses-json copied to clipboard
AttributeError: '_SpecialForm' object has no attribute '__args__'
File "\lib\site-packages\dataclasses_json\api.py", line 165, in schema
Schema = build_schema(cls, DataClassJsonMixin, infer_missing, partial)
File "\lib\site-packages\dataclasses_json\mm.py", line 349, in build_schema
schema_ = schema(cls, mixin, infer_missing)
File "\lib\site-packages\dataclasses_json\mm.py", line 301, in schema
if len(type_.__args__) == 2:
AttributeError: '_SpecialForm' object has no attribute '__args__'
This problem has started appearing following an upgrade from v0.3.7 to v0.3.8. Any idea what techniques I can use to debug why this is happening?
The bug appears to be introduced in commit e46dc2e381eed6cac26bf651116051a2de731196. The following example will raise the same exception:
from typing import Optional, Any
from dataclasses import dataclass
from dataclasses_json import dataclass_json
@dataclass_json
@dataclass
class SimpleExample:
int_field: int
any_field: Any
s = SimpleExample.schema()
The problem seems to be that for any_field
_is_optional()
will return True. Line 303 in mm.py below will throw an Exception since type_
is Any
which doesn't have __args__
instance variable:
if _is_optional(type_):
options.setdefault(missing_key, None)
options['allow_none'] = True
if len(type_.__args__) == 2:
...
A fix would be to hasattr(_type, '__args__') and len(type_.__args__)
such as:
if _is_optional(type_):
options.setdefault(missing_key, None)
options['allow_none'] = True
if hasattr(_type, '__args__') and len(type_.__args__) == 2:
...
Do you think you could make a pull request with this fix?
Related to https://github.com/lidatong/dataclasses-json/issues/174