From ee285cdd23c3c60a0df2154cc66365c82ff4d032 Mon Sep 17 00:00:00 2001 From: HongWeipeng Date: Tue, 21 Apr 2020 04:01:53 +0800 Subject: [PATCH] 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 --- Lib/test/test_typing.py | 7 +++++++ Lib/typing.py | 5 ++++- .../next/Library/2020-04-20-20-16-02.bpo-39942.NvGnTc.rst | 2 ++ 3 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2020-04-20-20-16-02.bpo-39942.NvGnTc.rst diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py index 6e7e5a210a6581..c141baf1a99a9a 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -218,6 +218,13 @@ def test_bound_errors(self): 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 1749c2fd35cd11..3deb1eac3b90f9 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -549,7 +549,10 @@ def __init__(self, name, *constraints, bound=None, 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 00000000000000..3b83037d170f6d --- /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.