dataclasses-json icon indicating copy to clipboard operation
dataclasses-json copied to clipboard

AttributeError: '_SpecialForm' object has no attribute '__args__'

Open davidbrown3 opened this issue 4 years ago • 3 comments

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?

davidbrown3 avatar Feb 10 '20 19:02 davidbrown3

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:
        ...

adamtec avatar Jun 19 '20 21:06 adamtec

Do you think you could make a pull request with this fix?

luni3359 avatar Sep 14 '21 04:09 luni3359

Related to https://github.com/lidatong/dataclasses-json/issues/174

matt035343 avatar Jun 16 '23 12:06 matt035343