Replies: 1 comment 1 reply
-
|
If you haven't already done so, I recommend reading the details in PEP 742, which introduced With that theory in mind, let's look at what's going on in your example above. In In Since the type of In In The spec says "In practice, the theoretic types for strict type guards cannot be expressed precisely in the Python type system. Type checkers should fall back on practical approximations of these types." So, I think the behavior you're seeing in There's a new type checker under development by Astral called "ty". It is the first major Python type checker that fully supports intersection and negation operations. It's still at the "alpha" stage of development, but once it's complete, it will likely be the first type checker that will be able to accurately represent these types internally. I tried your sample in the ty playground, and you can see that it accurately narrows the narrowed types. It doesn't (yet) correctly infer return types for |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
The Python
typingdocumentation describes structural types as "defines a set of values not by their__class__, but by their properties". It specifically mentions callable types and defines "a callable type is a subtype of another callable type based on their signatures, not a subclass relationship". I believe this rules work should forTypedDictandProtocoltoo, including genericProtocols.Here's what I found with Pyright (and mypy, too) and
TypeIs-based type narrowing:I thought this should be a bug? Maybe the current reduction rules are a little bit too aggressive. I would wish the static type checking to at least not conflict with the runtime behavior.
Beta Was this translation helpful? Give feedback.
All reactions