Skip to content

Commit 41660ca

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 887ff8e commit 41660ca

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

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

Lib/typing.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -600,7 +600,10 @@ def __init__(self, name, *constraints, bound=None,
600600
self.__bound__ = _type_check(bound, "Bound must be a type.")
601601
else:
602602
self.__bound__ = None
603-
def_mod = sys._getframe(1).f_globals['__name__'] # for pickling
603+
try:
604+
def_mod = sys._getframe(1).f_globals.get('__name__', '__main__') # for pickling
605+
except (AttributeError, ValueError):
606+
def_mod = None
604607
if def_mod != 'typing':
605608
self.__module__ = def_mod
606609

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)