Why is TypeIs Not Narrowing #11184
-
|
I do not know if this is a user bug or a problem in pyright. I will open an issue or fix my code. I am using Python 3.14.2 In the below code, I thought that adding the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
|
|
Beta Was this translation helpful? Give feedback.
Type narrowing is a static analysis concept, not a runtime concept. The
hasattrcall provides protection at runtime, but it has no effect at static analysis time because pyright doesn't recognize it as a type guard. In your code, the type ofvariableremains unchanged after thehasattrcall from the perspective of the type checker. The type ofvariableisNodeprior to the call, and it remains the same type after the call. SinceNodehas no attribute namedrelation, pyright reports an error when you attempt to access that attribute.In theory, it would be possible for a type checker to recognize
hasattras a valid type guard and perform narrowing by creating some internal (not expressible…