Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions crates/ty_python_semantic/resources/mdtest/attributes.md
Original file line number Diff line number Diff line change
Expand Up @@ -1791,6 +1791,80 @@ date.year = 2025
date.tz = "UTC"
```

### Return type of `__setattr__`

If the return type of the `__setattr__` method is `Never`, we do not allow any attribute assignments
on instances of that class:

```py
from typing_extensions import Never

class Frozen:
existing: int = 1

def __setattr__(self, name, value) -> Never:
raise AttributeError("Attributes can not be modified")

instance = Frozen()
instance.non_existing = 2 # error: [invalid-assignment] "Cannot assign to attribute `non_existing` on type `Frozen` whose `__setattr__` method returns `Never`/`NoReturn`"
instance.existing = 2 # error: [invalid-assignment] "Cannot assign to attribute `existing` on type `Frozen` whose `__setattr__` method returns `Never`/`NoReturn`"
```

### `__setattr__` on `object`

`object` has a custom `__setattr__` implementation, but we still emit an error if a non-existing
attribute is assigned on an `object` instance.

```py
obj = object()
obj.non_existing = 1 # error: [unresolved-attribute]
```

### Setting attributes on `Never` / `Any`

Setting attributes on `Never` itself should be allowed (even though it has a `__setattr__` attribute
of type `Never`):

```py
from typing_extensions import Never, Any

def _(n: Never):
reveal_type(n.__setattr__) # revealed: Never

# No error:
n.non_existing = 1
```

And similarly for `Any`:

```py
def _(a: Any):
reveal_type(a.__setattr__) # revealed: Any

# No error:
a.non_existing = 1
```

### Possibly unbound `__setattr__` method

If a `__setattr__` method is only partially bound, the behavior is still the same:

```py
from typing_extensions import Never

def flag() -> bool:
return True

class Frozen:
if flag():
def __setattr__(self, name, value) -> Never:
raise AttributeError("Attributes can not be modified")

instance = Frozen()
instance.non_existing = 2 # error: [invalid-assignment]
instance.existing = 2 # error: [invalid-assignment]
```

### `argparse.Namespace`

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