]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-39942:Fix failure in `TypeVar` when missing `__name__` (GH-19616)
authorHongWeipeng <hongweichen8888@sina.com>
Mon, 20 Apr 2020 20:01:53 +0000 (04:01 +0800)
committerGitHub <noreply@github.com>
Mon, 20 Apr 2020 20:01:53 +0000 (21:01 +0100)
https://bugs.python.org/issue39942

Lib/test/test_typing.py
Lib/typing.py
Misc/NEWS.d/next/Library/2020-04-20-20-16-02.bpo-39942.NvGnTc.rst [new file with mode: 0644]

index 489836c459b1c8edca38ace5c9217a0d4c3aed71..b3a671732167eb969a6876f100dcad094f7c6b29 100644 (file)
@@ -221,6 +221,13 @@ class TypeVarTests(BaseTestCase):
         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)
index df3650001e78ed694d7028aeba2ed3c2911d9388..9383fb8ff3a2369fab82594ac230601c2ff21816 100644 (file)
@@ -606,7 +606,10 @@ class TypeVar(_Final, _Immutable, _root=True):
             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 (file)
index 0000000..3b83037
--- /dev/null
@@ -0,0 +1,2 @@
+Set "__main__" as the default module name when "__name__" is missing in
+:class:`typing.TypeVar`. Patch by Weipeng Hong.