File tree Expand file tree Collapse file tree 2 files changed +789
-422
lines changed
crates/ty_python_semantic Expand file tree Collapse file tree 2 files changed +789
-422
lines changed Original file line number Diff line number Diff line change @@ -1685,6 +1685,60 @@ date.year = 2025
16851685date.tz = " UTC"
16861686```
16871687
1688+ ### Return type of ` __setattr__ `
1689+
1690+ If the return type of the ` __setattr__ ` method is ` Never ` , we do not allow any attribute assignments
1691+ on instances of that class:
1692+
1693+ ``` py
1694+ from typing_extensions import Never
1695+
1696+ class Frozen :
1697+ existing: int = 1
1698+
1699+ def __setattr__ (self , name , value ) -> Never:
1700+ raise AttributeError (" Attributes can not be modified" )
1701+
1702+ instance = Frozen()
1703+ instance.non_existing = 2 # error: [invalid-assignment]
1704+ instance.existing = 2 # error: [invalid-assignment]
1705+ ```
1706+
1707+ ### ` __setattr__ ` on ` object `
1708+
1709+ ` object ` has a custom ` __setattr__ ` implementation, but we still emit an error if a non-existing
1710+ attribute is assigned on an ` object ` instance.
1711+
1712+ ``` py
1713+ obj = object ()
1714+ obj.non_existing = 1 # error: [unresolved-attribute]
1715+ ```
1716+
1717+ ### Setting attributes on ` Never ` / ` Any `
1718+
1719+ Setting attributes on ` Never ` itself should be allowed (even though it has a ` __setattr__ ` attribute
1720+ of type ` Never ` ):
1721+
1722+ ``` py
1723+ from typing_extensions import Never, Any
1724+
1725+ def _ (n : Never):
1726+ reveal_type(n.__setattr__ ) # revealed: Never
1727+
1728+ # No error:
1729+ n.non_existing = 1
1730+ ```
1731+
1732+ And similarly for ` Any ` :
1733+
1734+ ``` py
1735+ def _ (a : Any):
1736+ reveal_type(a.__setattr__ ) # revealed: Any
1737+
1738+ # No error:
1739+ a.non_existing = 1
1740+ ```
1741+
16881742### ` argparse.Namespace `
16891743
16901744A standard library example of a class with a custom ` __setattr__ ` method is ` argparse.Namespace ` :
You can’t perform that action at this time.
0 commit comments