Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 35 additions & 23 deletions python2/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,7 @@
from typing import Pattern, Match
import typing
import weakref
try:
import collections.abc as collections_abc
except ImportError:
import collections as collections_abc # Fallback for PY3.2.
import collections
Comment thread
gvanrossum marked this conversation as resolved.
Resolved


class BaseTestCase(TestCase):
Expand Down Expand Up @@ -1055,7 +1052,7 @@ def test_supports_index(self):
self.assertIsSubclass(int, typing.SupportsIndex)
self.assertNotIsSubclass(str, typing.SupportsIndex)

def test_protocol_instance_type_error(self):
def test_protocol_instance_works(self):
self.assertIsInstance(0, typing.SupportsAbs)
self.assertNotIsInstance('no', typing.SupportsAbs)
class C1(typing.SupportsInt):
Expand All @@ -1066,6 +1063,21 @@ class C2(C1):
c = C2()
self.assertIsInstance(c, C1)

def test_collections_protocols_allowed(self):
@runtime_checkable
class Custom(collections.Iterable, Protocol):
def close(self): pass

class A(object): pass
class B(object):
def __iter__(self):
return []
def close(self):
return 0

self.assertIsSubclass(B, Custom)
self.assertNotIsSubclass(A, Custom)


class GenericTests(BaseTestCase):

Expand Down Expand Up @@ -1243,17 +1255,17 @@ def __len__(self):
return 0
# this should just work
MM().update()
self.assertIsInstance(MM(), collections_abc.MutableMapping)
self.assertIsInstance(MM(), collections.MutableMapping)
self.assertIsInstance(MM(), MutableMapping)
self.assertNotIsInstance(MM(), List)
self.assertNotIsInstance({}, MM)

def test_multiple_bases(self):
class MM1(MutableMapping[str, str], collections_abc.MutableMapping):
class MM1(MutableMapping[str, str], collections.MutableMapping):
pass
with self.assertRaises(TypeError):
# consistent MRO not possible
class MM2(collections_abc.MutableMapping, MutableMapping[str, str]):
class MM2(collections.MutableMapping, MutableMapping[str, str]):
pass

def test_orig_bases(self):
Expand Down Expand Up @@ -1426,9 +1438,9 @@ def __call__(self):

self.assertEqual(repr(C1[int]).split('.')[-1], 'C1[int]')
self.assertEqual(C2.__parameters__, ())
self.assertIsInstance(C2(), collections_abc.Callable)
self.assertIsSubclass(C2, collections_abc.Callable)
self.assertIsSubclass(C1, collections_abc.Callable)
self.assertIsInstance(C2(), collections.Callable)
self.assertIsSubclass(C2, collections.Callable)
self.assertIsSubclass(C1, collections.Callable)
self.assertIsInstance(T1(), tuple)
self.assertIsSubclass(T2, tuple)
self.assertIsSubclass(Tuple[int, ...], typing.Sequence)
Expand Down Expand Up @@ -2287,11 +2299,11 @@ def __len__(self):
self.assertIsSubclass(MMC, typing.Mapping)

self.assertIsInstance(MMB[KT, VT](), typing.Mapping)
self.assertIsInstance(MMB[KT, VT](), collections_abc.Mapping)
self.assertIsInstance(MMB[KT, VT](), collections.Mapping)

self.assertIsSubclass(MMA, collections_abc.Mapping)
self.assertIsSubclass(MMB, collections_abc.Mapping)
self.assertIsSubclass(MMC, collections_abc.Mapping)
self.assertIsSubclass(MMA, collections.Mapping)
self.assertIsSubclass(MMB, collections.Mapping)
self.assertIsSubclass(MMC, collections.Mapping)

self.assertIsSubclass(MMB[str, str], typing.Mapping)
self.assertIsSubclass(MMC, MMA)
Expand All @@ -2303,9 +2315,9 @@ class G(typing.Generator[int, int, int]): pass
def g(): yield 0
self.assertIsSubclass(G, typing.Generator)
self.assertIsSubclass(G, typing.Iterable)
if hasattr(collections_abc, 'Generator'):
self.assertIsSubclass(G, collections_abc.Generator)
self.assertIsSubclass(G, collections_abc.Iterable)
if hasattr(collections, 'Generator'):
self.assertIsSubclass(G, collections.Generator)
self.assertIsSubclass(G, collections.Iterable)
self.assertNotIsSubclass(type(g), G)

def test_subclassing_subclasshook(self):
Expand Down Expand Up @@ -2341,23 +2353,23 @@ class D: pass
self.assertIsSubclass(D, B)

class M(): pass
collections_abc.MutableMapping.register(M)
collections.MutableMapping.register(M)
self.assertIsSubclass(M, typing.Mapping)

def test_collections_as_base(self):

class M(collections_abc.Mapping): pass
class M(collections.Mapping): pass
self.assertIsSubclass(M, typing.Mapping)
self.assertIsSubclass(M, typing.Iterable)

class S(collections_abc.MutableSequence): pass
class S(collections.MutableSequence): pass
self.assertIsSubclass(S, typing.MutableSequence)
self.assertIsSubclass(S, typing.Iterable)

class I(collections_abc.Iterable): pass
class I(collections.Iterable): pass
self.assertIsSubclass(I, typing.Iterable)

class A(collections_abc.Mapping): pass
class A(collections.Mapping): pass
class B: pass
A.register(B)
self.assertIsSubclass(B, typing.Mapping)
Expand Down
8 changes: 7 additions & 1 deletion python2/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1759,6 +1759,11 @@ def utf8(value):
return _overload_dummy


_PROTO_WHITELIST = ['Callable', 'Iterable', 'Iterator',
'Hashable', 'Sized', 'Container', 'Collection',
'Reversible', 'ContextManager']


class _ProtocolMeta(GenericMeta):
"""Internal metaclass for Protocol.

Expand All @@ -1774,7 +1779,8 @@ def __init__(cls, *args, **kwargs):
for b in cls.__bases__)
if cls._is_protocol:
for base in cls.__mro__[1:]:
if not (base in (object, Generic, Callable) or
if not (base in (object, Generic) or
base.__module__ == '_abcoll' and base.__name__ in _PROTO_WHITELIST or
isinstance(base, TypingMeta) and base._is_protocol or
isinstance(base, GenericMeta) and base.__origin__ is Generic):
raise TypeError('Protocols can only inherit from other protocols,'
Expand Down
17 changes: 16 additions & 1 deletion typing_extensions/src_py3/test_typing_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from typing import no_type_check
from typing_extensions import NoReturn, ClassVar, Final, IntVar, Literal, Type, NewType, TypedDict
try:
from typing_extensions import Protocol, runtime
from typing_extensions import Protocol, runtime, runtime_checkable
except ImportError:
pass
try:
Expand Down Expand Up @@ -1391,6 +1391,21 @@ class E:
x = 1
self.assertIsInstance(E(), D)

def test_collections_protocols_allowed(self):
@runtime_checkable
class Custom(collections.abc.Iterable, Protocol):
def close(self): pass

class A: ...
class B:
def __iter__(self):
return []
def close(self):
return 0

self.assertIsSubclass(B, Custom)
self.assertNotIsSubclass(A, Custom)


class TypedDictTests(BaseTestCase):

Expand Down
14 changes: 12 additions & 2 deletions typing_extensions/src_py3/typing_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1080,6 +1080,12 @@ def _next_in_mro(cls):
return next_in_mro


_PROTO_WHITELIST = ['Callable', 'Awaitable',
'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator',
'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
'ContextManager', 'AsyncContextManager']


def _get_protocol_attrs(cls):
attrs = set()
for base in cls.__mro__[:-1]: # without object
Expand Down Expand Up @@ -1187,7 +1193,9 @@ def __init__(cls, *args, **kwargs):
for b in cls.__bases__)
if cls._is_protocol:
for base in cls.__mro__[1:]:
if not (base in (object, Generic, Callable) or
if not (base in (object, Generic) or
base.__module__ == 'collections.abc' and

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe there's a bug here because _PROTO_WHITELIST contains ContextManager and AsyncContextManager but neither of those come from the collections.abc module. This makes code like the following fail:

In [24]: from typing import ContextManager
    ...: from typing_extensions import Protocol
    ...:
    ...: class Foobar(ContextManager, Protocol):
    ...:     pass
    ...:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-fa1f28400733> in <module>
      1 from typing import ContextManager
      2
----> 3 class Foobar(ContextManager, Protocol):
      4     pass
      5

/mnt/xarfuse/uid-4861/0260e378-ns-4026531840/typing_extensions.py in __init__(cls, *args, **kwargs)
   1201                             base.__origin__ is Generic):
   1202                         raise TypeError('Protocols can only inherit from other'
-> 1203                                         ' protocols, got %r' % base)
   1204
   1205                 def _no_init(self, *args, **kwargs):

TypeError: Protocols can only inherit from other protocols, got typing.ContextManager

Is there something I'm missing here, or is there genuinely an issue that needs to be fixed by maintaining a map of module -> class name for everything in the _PROTO_WHITELIST list?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this happen on all Python versions? I think it may be relevant only for 3.5, if not however it makes sense to fix this by making whitelisting more precise.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll see if I can repro in 2.7 as well, my error is from 3.6.

If it is 3.5+ only, would you have an alternate suggestion apart from having a more explicit module -> class name whitelist?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can repro this in 2.7 as well:

In [4]: from typing import ContextManager
   ...: from typing_extensions import Protocol
   ...:
   ...: class Foobar(ContextManager, Protocol):
   ...:     pass
   ...:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-b18f9414f140> in <module>()
      2 from typing_extensions import Protocol
      3
----> 4 class Foobar(ContextManager, Protocol):
      5     pass

/data/users/divij/fbsource/fbcode/buck-out/dev/gen/experimental/divij/test_smc_db_types-ipython#link-tree/typing_extensions.py in __init__(cls, *args, **kwargs)
    187                         isinstance(base, GenericMeta) and base.__origin__ is Generic):
    188                     raise TypeError('Protocols can only inherit from other protocols,'
--> 189                                     ' got %r' % base)
    190             cls._callable_members_only = all(callable(getattr(cls, attr))
    191                                              for attr in cls._get_protocol_attrs())

TypeError: Protocols can only inherit from other protocols, got typing.ContextManager

In [5]: import sys

In [6]: sys.version
Out[6]: '2.7.14 (default, May 13 2019, 13:45:19) \n[GCC 7.x 20190403 (Facebook) 8.x]'

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like there is a bigger problem. I can reproduce this also in Python 3.8 (beta) and Protocol imported from typing. I think we need to fix it there first, and then apply the fix to this backport. The simplest fix may be indeed to keep the mapping. Could you please open an issue on https://bugs.python.org?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, I'll do that right now. Thanks for following up @ilevkivskyi!

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Created https://bugs.python.org/issue38008, I'll move the discussion there

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jivid Now that this is fixed upstream, would you like to work on a backport?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ilevkivskyi yes! Is it enough for me to make a similar change to the original PR in this repo, or do I need to do something else for backporting?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it enough for me to make a similar change to the original PR in this repo, or do I need to do something else for backporting?

I don't remember for sure TBH, but most likely yes. Note however that you might need to add this change to more than one place. There are four places that might need to be updated: typing_extensions/src_py2, typing_extensions/src_py3, src, and python2. Also you would need to add tests for all of these versions (even if some of them already work).

base.__name__ in _PROTO_WHITELIST or
isinstance(base, TypingMeta) and base._is_protocol or
isinstance(base, GenericMeta) and
base.__origin__ is Generic):
Expand Down Expand Up @@ -1513,7 +1521,9 @@ def _proto_hook(other):

# Check consistency of bases.
for base in cls.__bases__:
if not (base in (object, Generic, Callable) or
if not (base in (object, Generic) or
base.__module__ == 'collections.abc' and
base.__name__ in _PROTO_WHITELIST or
isinstance(base, _ProtocolMeta) and base._is_protocol):
raise TypeError('Protocols can only inherit from other'
' protocols, got %r' % base)
Expand Down