-
Notifications
You must be signed in to change notification settings - Fork 234
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
isinstance
check with nested Protocol
.
#1257
Comments
isinstance
check with Protocol
with isinstance
check with nested Protocol
.
This is a big can of worms and I don't think it's a good idea to add it to the standard library. For example, we'd have to get runtime checks for TypeVars, and generic types, and callable compatibility. |
Just wondering, is there any clean way to do structural typing for more complex objects? E.g. def isbarlike(obj) -> TypeGuard[BarLike]
.... looks useful, but really isn't because all we learn is that def isabar(obj) -> TypeGuard[Bar] # functionally equivalent to ``isinstance(obj, Bar)``
.... but that defeats the intent of static duck typing. |
The semantics of If you want to apply different semantics (e.g. perform deeper nested checks), you can write your own implementation. If you use
If def isfoolike(obj) -> TypeGuard[FooLike]:
return hasattr(obj, 'attr') and isinstance(obj.attr, str)
def isbarlike(obj) -> TypeGuard[BarLike]:
return hasattr(obj, 'attr') and isfoolike(obj.attr) |
isinstance(obj, ProtocolSubclass)
only checks the the existence ofProtocolSubclass
's methods onobj
and not the type signature. To provide deeper checks, maybeisinstance
could check attributes/methods onProtocolSubclass
that are themselves aProtocol
.A small example showing the change in behavior:
The text was updated successfully, but these errors were encountered: