Skip to content

Commit 4265911

Browse files
committed
Add initial set of tests
1 parent d113662 commit 4265911

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

crates/ty_python_semantic/resources/mdtest/attributes.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1628,6 +1628,60 @@ date.year = 2025
16281628
date.tz = "UTC"
16291629
```
16301630

1631+
### Return type of `__setattr__`
1632+
1633+
If the return type of the `__setattr__` method is `Never`, we do not allow any attribute assignments
1634+
on instances of that class:
1635+
1636+
```py
1637+
from typing_extensions import Never
1638+
1639+
class Frozen:
1640+
existing: int = 1
1641+
1642+
def __setattr__(self, name, value) -> Never:
1643+
raise AttributeError("Attributes can not be modified")
1644+
1645+
instance = Frozen()
1646+
instance.non_existing = 2 # error: [invalid-assignment]
1647+
instance.existing = 2 # error: [invalid-assignment]
1648+
```
1649+
1650+
### `__setattr__` on `object`
1651+
1652+
`object` has a custom `__setattr__` implementation, but we still emit an error if a non-existing
1653+
attribute is assigned on an `object` instance.
1654+
1655+
```py
1656+
obj = object()
1657+
obj.non_existing = 1 # error: [unresolved-attribute]
1658+
```
1659+
1660+
### Setting attributes on `Never` / `Any`
1661+
1662+
Setting attributes on `Never` itself should be allowed (even though it has a `__setattr__` attribute
1663+
of type `Never`):
1664+
1665+
```py
1666+
from typing_extensions import Never, Any
1667+
1668+
def _(n: Never):
1669+
reveal_type(n.__setattr__) # revealed: Never
1670+
1671+
# No error:
1672+
n.non_existing = 1
1673+
```
1674+
1675+
And similarly for `Any`:
1676+
1677+
```py
1678+
def _(a: Any):
1679+
reveal_type(a.__setattr__) # revealed: Any
1680+
1681+
# No error:
1682+
a.non_existing = 1
1683+
```
1684+
16311685
### `argparse.Namespace`
16321686

16331687
A standard library example of a class with a custom `__setattr__` method is `argparse.Namespace`:

0 commit comments

Comments
 (0)