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

Order of annotations matters?

Open allquixotic opened this issue 2 years ago • 2 comments

This cost me several hours to figure this out, so I thought I would share it here and see if there is any way for this library to improve the behavior or at least make the error clearer.

Example 1, from the docs, works fine:

from dataclasses_json import dataclass_json


@dataclass_json
@dataclass
class Person:
    name: str

person = Person(name='lidatong')

Example 2 fails:

from dataclasses_json import dataclass_json


@dataclass
@dataclass_json
class Person:
    name: str


person = Person(name='lidatong')

The only difference in the source of Example 2 is that the order of the annotations is flipped - @dataclass first, then @dataclass_json. The error is TypeError: Person() takes no arguments. Indeed, the type only has a zero-args constructor when the annotations are defined in this order.

allquixotic avatar Mar 25 '22 13:03 allquixotic

I"ve found the same thing and accepted it as a quirk of the library - more challenging is that it appears to hide introspection in PyCharm (auto-complete doesn't populate with the dataclass fields)

cmcconomyfwig avatar Mar 30 '22 13:03 cmcconomyfwig

To be fair, the documentation does clearly say that the order of the decorators matter: https://github.com/lidatong/dataclasses-json#approach-1-class-decorator

I do agree that a better error message could be nice.

Abou the IDE integration/auto-complete : using DataClassJsonMixin instead of the decorator is an easy way to make IDEs and linter happier, as documented too. (personally I no longer use the @dataclass_json decorator at all)

florianlh avatar Mar 30 '22 13:03 florianlh

Closing as this is clearly stated in docs - order of decorators unfortunately matters in Python.

george-zubrienko avatar Jun 11 '23 17:06 george-zubrienko