mirror of
https://github.com/astral-sh/ruff.git
synced 2025-10-01 06:11:21 +00:00
[ty] Narrowing for hasattr()
(#18053)
This commit is contained in:
parent
a97e72fb5e
commit
c7b6108cb8
5 changed files with 105 additions and 20 deletions
26
crates/ty_python_semantic/resources/mdtest/narrow/hasattr.md
Normal file
26
crates/ty_python_semantic/resources/mdtest/narrow/hasattr.md
Normal file
|
@ -0,0 +1,26 @@
|
|||
# Narrowing using `hasattr()`
|
||||
|
||||
The builtin function `hasattr()` can be used to narrow nominal and structural types. This is
|
||||
accomplished using an intersection with a synthesized protocol:
|
||||
|
||||
```py
|
||||
from typing import final
|
||||
|
||||
class Foo: ...
|
||||
|
||||
@final
|
||||
class Bar: ...
|
||||
|
||||
def f(x: Foo):
|
||||
if hasattr(x, "spam"):
|
||||
reveal_type(x) # revealed: Foo & <Protocol with members 'spam'>
|
||||
reveal_type(x.spam) # revealed: object
|
||||
|
||||
if hasattr(x, "not-an-identifier"):
|
||||
reveal_type(x) # revealed: Foo
|
||||
|
||||
def y(x: Bar):
|
||||
if hasattr(x, "spam"):
|
||||
reveal_type(x) # revealed: Never
|
||||
reveal_type(x.spam) # revealed: Never
|
||||
```
|
Loading…
Add table
Add a link
Reference in a new issue