Skip to content
Discussion options

You must be logged in to vote

Type narrowing is a static analysis concept, not a runtime concept. The hasattr call 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 of variable remains unchanged after the hasattr call from the perspective of the type checker. The type of variable is Node prior to the call, and it remains the same type after the call. Since Node has no attribute named relation, pyright reports an error when you attempt to access that attribute.

In theory, it would be possible for a type checker to recognize hasattr as a valid type guard and perform narrowing by creating some internal (not expressible…

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@CraigMilhiserBrivo
Comment options

@erictraut
Comment options

Answer selected by CraigMilhiserBrivo
@CraigMilhiserBrivo
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants