Skip to content

Commit a25a04f

Browse files
authored
bpo-39942:Fix failure in TypeVar when missing __name__ (GH-19616)
https://bugs.python.org/issue39942
1 parent eba9f61 commit a25a04f

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
@@ -221,6 +221,13 @@ def test_bound_errors(self):
221221
with self.assertRaises(TypeError):
222222
TypeVar('X', str, float, bound=Employee)
223223

224+
def test_missing__name__(self):
225+
# See bpo-39942
226+
code = ("import typing\n"
227+
"T = typing.TypeVar('T')\n"
228+
)
229+
exec(code, {})
230+
224231
def test_no_bivariant(self):
225232
with self.assertRaises(ValueError):
226233
TypeVar('T', covariant=True, contravariant=True)

Lib/typing.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -606,7 +606,10 @@ def __init__(self, name, *constraints, bound=None,
606606
self.__bound__ = _type_check(bound, "Bound must be a type.")
607607
else:
608608
self.__bound__ = None
609-
def_mod = sys._getframe(1).f_globals['__name__'] # for pickling
609+
try:
610+
def_mod = sys._getframe(1).f_globals.get('__name__', '__main__') # for pickling
611+
except (AttributeError, ValueError):
612+
def_mod = None
610613
if def_mod != 'typing':
611614
self.__module__ = def_mod
612615

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)