How to do the most fundamental duck-typing with Protocols
?
#1525
Unanswered
randolf-scholz
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
How does one implement the most essential duck typing with
typing.Protocol
? Specifically, how to write aProtocol
-class such that an instanceobj
of a (non-protocol) subtype has to satisfy:hasattr(obj, name)
isinstance(obj.name, T)
How the subclass manages to satisfy these conditions is irrelevant. Python offers multiple builtin-options: basic attributes,
ClassVar
,@property
,@cached_property
. Here, we do not care if it is mutable or not, all we want is thatobj.name
gives aT
. However, these are considered mutually incompatible by different type checkers, in fact, I made a compatibility chart (mypy
1.7.1 /pyright
1.1.339):Source
EDIT: Fixed wrong data entry in table.
Question: How to write a
Protocol
that is essentially equivalent to statically asserting (1) and (2), and nothing more?It seems not even a workaround like the following is not feasible, since
property
is not generic.Beta Was this translation helpful? Give feedback.
All reactions