Last active
September 23, 2018 16:40
-
-
Save 1st1/37fdd3cc84cd65b9af3471b935b722df to your computer and use it in GitHub Desktop.
A hack-ish way to fix dataclasses & get_type_hints()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py | |
index 28e9f75127..ad3dc46b67 100644 | |
--- a/Lib/dataclasses.py | |
+++ b/Lib/dataclasses.py | |
@@ -868,7 +868,7 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen): | |
# Include InitVars and regular fields (so, not ClassVars). | |
flds = [f for f in fields.values() | |
if f._field_type in (_FIELD, _FIELD_INITVAR)] | |
- _set_new_attribute(cls, '__init__', | |
+ had_own_init = _set_new_attribute(cls, '__init__', | |
_init_fn(flds, | |
frozen, | |
has_post_init, | |
@@ -878,6 +878,9 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen): | |
'__dataclass_self__' if 'self' in fields | |
else 'self', | |
)) | |
+ if not had_own_init: | |
+ cls.__init__.__module__ = cls.__module__ | |
+ cls.__init__.__generated__ = True | |
# Get the fields as a list, and include only real fields. This is | |
# used in all of the following methods. | |
diff --git a/Lib/typing.py b/Lib/typing.py | |
index 445a42492b..3f6a916b6c 100644 | |
--- a/Lib/typing.py | |
+++ b/Lib/typing.py | |
@@ -978,7 +978,10 @@ def get_type_hints(obj, globalns=None, localns=None): | |
if isinstance(obj, types.ModuleType): | |
globalns = obj.__dict__ | |
else: | |
- globalns = getattr(obj, '__globals__', {}) | |
+ if hasattr(obj, '__generated__'): | |
+ globalns = sys.modules[obj.__module__].__dict__ | |
+ else: | |
+ globalns = getattr(obj, '__globals__', {}) | |
if localns is None: | |
localns = globalns | |
elif localns is None: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another way to fix this:
exec()
to accept arbitrary Mappings forglobals
;__globals__
attribute on functions it generates to a ModuleProxy mapping like the following: