[issue34776] Postponed annotations break inspection of dataclasses

Yury Selivanov report at bugs.python.org
Sun Sep 23 14:31:42 EDT 2018


Yury Selivanov <yselivanov at gmail.com> added the comment:

> See this for Yury's self-described "hack-ish fix we can use" until we do something better:

Actually, I think I found a better solution that doesn't require any changes to anything besides dataclasses.

Currently, dataclasses uses 'exec()' function to dynamically create methods like '__init__'.  The generated code for '__init__' needs to access MISSING and _HAS_DEFAULT_FACTORY constants from the dataclasses module.  To do that, we compile the code with 'exec()' with globals set to a dict with {MISSING, _HAS_DEFAULT_FACTORY} keys in it.  This does the trick, but '__init__.__globals__' ends up pointing to that custom dict, instead of pointing to the module's dict.

The other way around is to use a closure around __init__ to inject MISSING and _HAS_DEFAULT_FACTORY values *and* to compile the code in a proper __dict__ of the module the dataclass was defined in.  Please take a look at the PR.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue34776>
_______________________________________


More information about the Python-bugs-list mailing list