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

Builtin classes have a register method, because of Protocol inheritance #13466

Open
davidhalter opened this issue Feb 5, 2025 · 0 comments
Open

Comments

@davidhalter
Copy link
Contributor

Builtin classes str and list inherit from Sequence and indirectly from Protocol, which implies that register is available for those classes, which is not correct.

In Python it is possible to use register on a Protocol, but not on str:

>>> from typing import Protocol
>>> class Foo(Protocol):
...  x: str
... 
>>> Foo.register(int)
<class 'int'>
>>> str.register(int)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'str' has no attribute 'register'

In Mypy it is valid to use register on Protocols, but it's also possible to write str.register(int) or list.register(int), which is incorrect.

In Pyright register doesn't work on all protocols:

from typing import Protocol
list.register(int)  # Doesn't work (which is correct)

class Foo(Protocol):
    x: str

Foo.register(int)  # Also doesn't work (but it should)

So it feels that both Mypy and Pyright are not correct here and typeshed itself doesn't really help. I feel it is kind of wrong that str and list inherit from Protocols, but I can understand that it reduces a lot of duplicate code in stubs. Is there another way how we could improve this situation? Should we add a marker for those cases where a class inherits from a Protocol in typeshed, but is not really a Protocol during runtime?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant