Skip to content

Commit 694a95f

Browse files
bpo-39942:Fix failure in TypeVar when missing __name__ (GH-19616)
https://bugs.python.org/issue39942 (cherry picked from commit a25a04f) Co-authored-by: HongWeipeng <[email protected]>
1 parent d0d4e33 commit 694a95f

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

Lib/test/test_typing.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,13 @@ def test_bound_errors(self):
218218
with self.assertRaises(TypeError):
219219
TypeVar('X', str, float, bound=Employee)
220220

221+
def test_missing__name__(self):
222+
# See bpo-39942
223+
code = ("import typing\n"
224+
"T = typing.TypeVar('T')\n"
225+
)
226+
exec(code, {})
227+
221228
def test_no_bivariant(self):
222229
with self.assertRaises(ValueError):
223230
TypeVar('T', covariant=True, contravariant=True)

Lib/typing.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -549,7 +549,10 @@ def __init__(self, name, *constraints, bound=None,
549549
self.__bound__ = _type_check(bound, "Bound must be a type.")
550550
else:
551551
self.__bound__ = None
552-
def_mod = sys._getframe(1).f_globals['__name__'] # for pickling
552+
try:
553+
def_mod = sys._getframe(1).f_globals.get('__name__', '__main__') # for pickling
554+
except (AttributeError, ValueError):
555+
def_mod = None
553556
if def_mod != 'typing':
554557
self.__module__ = def_mod
555558

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Set "__main__" as the default module name when "__name__" is missing in
2+
:class:`typing.TypeVar`. Patch by Weipeng Hong.

0 commit comments

Comments
 (0)