Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exclude the same special attributes from Protocol as CPython #15490

Merged
merged 6 commits into from
Jun 26, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
20 changes: 20 additions & 0 deletions mypy/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3017,6 +3017,24 @@ class is generic then it will be a type constructor of higher kind.
"is_intersection",
]

# Special attributes not collected as protocol members by Python 3.12
# See typing._SPECIAL_NAMES
EXCLUDED_ATTRIBUTES: Final = frozenset(
Copy link
Member

Choose a reason for hiding this comment

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

I think that module level constant is better :)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I moved it back above the class. Unless it should go somewhere else.

{
"__abstractmethods__",
"__annotations__",
"__dict__",
"__doc__",
"__init__",
Copy link
Member

Choose a reason for hiding this comment

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

CC @AlexWaygood about that

Copy link
Member

Choose a reason for hiding this comment

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

I think excluding __init__ and __new__ makes sense. As @HexDecimal says, it's what CPython does: https://github.com/python/cpython/blob/4328dc646517f9251bdf6c827014f01c5229e8d9/Lib/typing.py#L1678-L1682

In general, constructors and initialisers aren't thought to be relevant to whether or not a class abides by the Liskov Substitution Principle. In general, there's no guarantee that just because class X is a subtype of class Y, class X's initialiser will therefore be compatible with class Y's initialiser.

Copy link
Member

Choose a reason for hiding this comment

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

Python had a change in 3.11 so that __init__ methods on protocol base classes are preserved in concrete subclasses of that protocol, but it still doesn't an consider __init__ method a protocol member for the purposes of isinstance() or issubclass() checks, I don't think

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I found an old discussion of this topic at #3823.

"__module__",
"__new__",
Copy link
Member

Choose a reason for hiding this comment

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

I am also not sure about __new__. I think that there might be valid use-case for it.

"__slots__",
"__subclasshook__",
"__weakref__",
"__class_getitem__", # Since Python 3.9
}
)

def __init__(self, names: SymbolTable, defn: ClassDef, module_name: str) -> None:
"""Initialize a TypeInfo."""
super().__init__()
Expand Down Expand Up @@ -3115,6 +3133,8 @@ def protocol_members(self) -> list[str]:
if isinstance(node.node, (TypeAlias, TypeVarExpr, MypyFile)):
# These are auxiliary definitions (and type aliases are prohibited).
continue
if name in self.EXCLUDED_ATTRIBUTES:
continue
members.add(name)
return sorted(list(members))

Expand Down
59 changes: 59 additions & 0 deletions test-data/unit/check-protocols.test
Original file line number Diff line number Diff line change
Expand Up @@ -2789,6 +2789,65 @@ class A(Protocol):

[builtins fixtures/tuple.pyi]

[case testProtocolSlotsIsNotProtocolMember]
# https://github.com/python/mypy/issues/11884
from typing import Protocol

class Foo(Protocol):
__slots__ = ()
class NoSlots:
pass
class EmptySlots:
__slots__ = ()
class TupleSlots:
__slots__ = ('x', 'y')
class StringSlots:
__slots__ = 'x y'
def foo(f: Foo):
pass

# All should pass:
foo(NoSlots())
foo(EmptySlots())
foo(TupleSlots())
foo(StringSlots())
[builtins fixtures/tuple.pyi]

[case testProtocolSlotsAndRuntimeCheckable]
from typing import Protocol, runtime_checkable

@runtime_checkable
class Foo(Protocol):
__slots__ = ()
class Bar:
pass
issubclass(Bar, Foo) # Used to be an error, when `__slots__` counted as a protocol member
[builtins fixtures/isinstance.pyi]
[typing fixtures/typing-full.pyi]


[case testProtocolWithClassGetItem]
# https://github.com/python/mypy/issues/11886
from typing import Any, Iterable, Protocol, Union

class B:
...

class C:
def __class_getitem__(cls, __item: Any) -> Any:
...

class SupportsClassGetItem(Protocol):
__slots__: Union[str, Iterable[str]] = ()
def __class_getitem__(cls, __item: Any) -> Any:
...

b1: SupportsClassGetItem = B()
c1: SupportsClassGetItem = C()
[builtins fixtures/tuple.pyi]
[typing fixtures/typing-full.pyi]


[case testNoneVsProtocol]
# mypy: strict-optional
from typing_extensions import Protocol
Expand Down