GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Relaxing usage of `type` with `typing.Protocol` in typing spec · Issue #2306 · python/typing Open Labels topic: typing specFor improving the typing specFor improving the typing spec DescriptionSome time ago I opened a thread on the Python discourse about implementing an Consider the snippet: from abc import abstractmethod from typing import runtime_checkable, Protocol, TypeVar, TypeGuard @runtime_checkable class MyProtocol(Protocol): @abstractmethod def my_method(self) -> str: ... class MyClass: def my_method(self) -> str: return "Hello from MyClass!" class MyOtherClass: def another_method(self) -> str: return "Hello from MyOtherClass!" P = TypeVar('P', bound=MyProtocol) def check_protocol(obj: object, protocol: type[P]) -> TypeGuard[P]: return isinstance(obj, protocol) # Example usage my_obj = MyClass() my_other_obj = MyOtherClass() if check_protocol(my_obj, MyProtocol): print(my_obj.my_method()) if check_protocol(my_other_obj, MyProtocol): print(my_other_obj.my_method()) else: print("Object does not implement MyProtocol.") Output: At runtime, this works as intended. At type checking time, According to the typing specification, I was hoping for more discussion points presented in the thread but not many replied. I didn't want to monopolize it, so I'm trying my luck here. @JelleZijlstra (sorry for the ping) did point out that it might be worthwhile to change the spec to allow this behavior but I'm guessing there should be some discussion on how to deal with it first. Jelle suggested: "If you want it to be instantiable, use I do agree it makes sense, but this snippet: from typing import Protocol class MyProtocol(Protocol): def method(self) -> str: ... print(callable(MyProtocol)) # prints True confuses me. So my point is: could the spec allow for I tried adding the "typing spec" label but couldn't. At any rate, thank you for the consideration. Reacted by Kris Kaczor Activity
MetadataMetadataAssigneesLabelstopic: typing specFor improving the typing specFor improving the typing spec ProjectsMilestoneRelationshipsDevelopmentIssue actions |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |