basedpyright
basedpyright copied to clipboard
Add type narrowing for hasattr() guards
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:
- PyRight doesn't narrow type based on hasattr #6717
- hasattr on await should narrow to Awaitable #5860
- Type inference based on hasattr checks #5964
-
PyRight doesn't narrow type based on
hasattr#6717 - Pydantic models are ignoring hasattr checks for pyright #6897
- hasattr(obj, 'slots') does not allow access to obj.slots #7363
- Getting "Cannot access member" error when inside a hasattr check pylance-release#2237