basedpyright icon indicating copy to clipboard operation
basedpyright copied to clipboard

Add type narrowing for hasattr() guards

Open diego-pm opened this issue 9 months ago • 0 comments

Description

It would be very helpful if basedpyright did type narrowing based on conditions of hasattr(), locals(), and globals().

One use case example where this would be useful is:

try:
    a = foo()
    # more code here...
except:
    if 'a' in locals():
        print(a)

Currently, the last statement would show a basedpyright error because it thinks the a variable is possibly unbound. Similar cases would be when using the clauses 'a' in globals() or hasattr() in the if statement.

This feature has been requested several times in pyright, but it is not planned:

diego-pm avatar Apr 14 '25 11:04 diego-pm