diff options
author | Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> | 2020-04-20 20:24:35 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-04-20 20:24:35 (GMT) |
commit | 41660cac63c1a216e43335007e329e213054100e (patch) | |
tree | a064da64f7a23e52220923aad6675c5567028979 | |
parent | 887ff8e37e238fbce18c647e588283904f38ab24 (diff) | |
download | cpython-41660cac63c1a216e43335007e329e213054100e.zip cpython-41660cac63c1a216e43335007e329e213054100e.tar.gz cpython-41660cac63c1a216e43335007e329e213054100e.tar.bz2 |
bpo-39942:Fix failure in `TypeVar` when missing `__name__` (GH-19616)
https://bugs.python.org/issue39942
(cherry picked from commit a25a04fea5446b1712cde0cff556574be139285a)
Co-authored-by: HongWeipeng <hongweichen8888@sina.com>
-rw-r--r-- | Lib/test/test_typing.py | 7 | ||||
-rw-r--r-- | Lib/typing.py | 5 | ||||
-rw-r--r-- | Misc/NEWS.d/next/Library/2020-04-20-20-16-02.bpo-39942.NvGnTc.rst | 2 |
3 files changed, 13 insertions, 1 deletions
diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py index ded5a8b..bdd7acd 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -220,6 +220,13 @@ class TypeVarTests(BaseTestCase): with self.assertRaises(TypeError): TypeVar('X', str, float, bound=Employee) + def test_missing__name__(self): + # See bpo-39942 + code = ("import typing\n" + "T = typing.TypeVar('T')\n" + ) + exec(code, {}) + def test_no_bivariant(self): with self.assertRaises(ValueError): TypeVar('T', covariant=True, contravariant=True) diff --git a/Lib/typing.py b/Lib/typing.py index 7aab8db..f4fb08f 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -600,7 +600,10 @@ class TypeVar(_Final, _Immutable, _root=True): self.__bound__ = _type_check(bound, "Bound must be a type.") else: self.__bound__ = None - def_mod = sys._getframe(1).f_globals['__name__'] # for pickling + try: + def_mod = sys._getframe(1).f_globals.get('__name__', '__main__') # for pickling + except (AttributeError, ValueError): + def_mod = None if def_mod != 'typing': self.__module__ = def_mod diff --git a/Misc/NEWS.d/next/Library/2020-04-20-20-16-02.bpo-39942.NvGnTc.rst b/Misc/NEWS.d/next/Library/2020-04-20-20-16-02.bpo-39942.NvGnTc.rst new file mode 100644 index 0000000..3b83037 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2020-04-20-20-16-02.bpo-39942.NvGnTc.rst @@ -0,0 +1,2 @@ +Set "__main__" as the default module name when "__name__" is missing in +:class:`typing.TypeVar`. Patch by Weipeng Hong. |