Skip to content

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

Closed as duplicate

Description

@davidhalter

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?

Activity

  1. srittau commented on Feb 26, 2025

    @srittau
    Collaborator

    That's an unfortunate side-effect of Sequence not being a protocol and therefore several types having to inherit from it. A similar situation to typing.IO. I think Sequence is overused and we should have a protocol alternative for the most common use cases, but the unfortunate fact of the matter is that we don't, so we're stuck with the current situation at the moment.

    But in the end this is something we can't change in typeshed, so maybe that's something to bring up on discuss.python.org or in the typing repository.

  2. AlexWaygood commented on Feb 26, 2025

    @AlexWaygood
    Member

    I think this is essentially a duplicate of #1595

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions