Skip to content

Commit f4e7b23

Browse files
authored
Fix unions of protocols on Python 2 (#654)
Fixes #488 (again). The fix is a hack, but on the other hand it was always a hack. Using this opportunity I also remove some unused imports in Python 2 tests.
1 parent 27f2e42 commit f4e7b23

File tree

3 files changed

+11
-12
lines changed

3 files changed

+11
-12
lines changed

python2/test_typing.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -988,12 +988,12 @@ def __init__(self):
988988
self.assertIsInstance(C(), P)
989989
self.assertIsInstance(D(), P)
990990

991-
def test_protocols_in_unions(self):
992-
class P(Protocol):
993-
x = None # type: int
994-
Alias = typing.Union[typing.Iterable, P]
995-
Alias2 = typing.Union[P, typing.Iterable]
996-
self.assertEqual(Alias, Alias2)
991+
def test_protocols_in_unions(self):
992+
class P(Protocol):
993+
x = None # type: int
994+
Alias = typing.Union[typing.Iterable, P]
995+
Alias2 = typing.Union[P, typing.Iterable]
996+
self.assertEqual(Alias, Alias2)
997997

998998
def test_protocols_pickleable(self):
999999
global P, CP # pickle wants to reference the class by name

python2/typing.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1834,7 +1834,9 @@ def __instancecheck__(self, instance):
18341834
def __subclasscheck__(self, cls):
18351835
if (self.__dict__.get('_is_protocol', None) and
18361836
not self.__dict__.get('_is_runtime_protocol', None)):
1837-
if sys._getframe(1).f_globals['__name__'] in ['abc', 'functools']:
1837+
if (sys._getframe(1).f_globals['__name__'] in ['abc', 'functools'] or
1838+
# This is needed because we remove subclasses from unions on Python 2.
1839+
sys._getframe(2).f_globals['__name__'] == 'typing'):
18381840
return False
18391841
raise TypeError("Instance and class checks can only be used with"
18401842
" @runtime_checkable protocols")

typing_extensions/src_py2/test_typing_extensions.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,13 @@
11
import sys
22
import os
3-
import abc
43
import contextlib
54
import collections
6-
import pickle
75
import subprocess
8-
import types
9-
from unittest import TestCase, main, skipUnless
6+
from unittest import TestCase, main
107

118
from typing_extensions import Annotated, NoReturn, ClassVar, Final, IntVar, Literal, TypedDict
129
from typing_extensions import ContextManager, Counter, Deque, DefaultDict
13-
from typing_extensions import NewType, overload, Protocol, runtime
10+
from typing_extensions import NewType, overload
1411
from typing import Dict, List
1512
import typing
1613
import typing_extensions

0 commit comments

Comments
 (0)