Skip to content

Commit

Permalink
bpo-39942:Fix failure in TypeVar when missing __name__ (GH-19616)
Browse files Browse the repository at this point in the history
https://bugs.python.org/issue39942
(cherry picked from commit a25a04f)

Co-authored-by: HongWeipeng <hongweichen8888@sina.com>
  • Loading branch information
miss-islington and HongWeipeng committed Apr 20, 2020
1 parent 887ff8e commit 41660ca
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 1 deletion.
7 changes: 7 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,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)
Expand Down
5 changes: 4 additions & 1 deletion Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -600,7 +600,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

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Set "__main__" as the default module name when "__name__" is missing in
:class:`typing.TypeVar`. Patch by Weipeng Hong.

0 comments on commit 41660ca

Please sign in to comment.