PEP 767: Annotating Read-Only Attributes

In theory, the type system is capable of expressing the distinction, even if type-checkers usually don’t do it this way. The trick is that the whole interface of a class can in principle be translated into one big overload of the __getattr__ and __setattr__ methods:

class Foo
    attr1: str
    attr2: Final[int]
    def method1(self, x: int) -> int: ...

# can in theory be translated to something like
class Foo:
    @overload
    def __getattr__(self, key: Literal["attr1"]) -> str: ...
    @overload
    def __getattr__(self, key: Literal["attr2"]) -> int: ...
    @overload
    def __getattr__(self, key: Literal["method1"]) -> Callable[[int], int]: ...

    @overload
    def __setattr__(self, key: Literal["attr1"], value: str) -> None: ...
    @overload
    def __setattr__(self, key: Literal["attr2"], value: int) -> Never: ...

We can precisely formalize the behavior of Readable and ReadOnly as contracts on __getattr__ and __setattr__ as follows

# name: Readable[T] induces a contract only on __getattr__
def __getattr__(self, key: Literal["name"]) -> T: ...
# name: ReadOnly[T] induces a contract on both __getattr__ and __setattr__
def __getattr__(self, key: Literal["name"]) -> T: ...
def __setattr__(self, key: Literal["name"], value: T) -> Never: ...

This also makes it obvious that Readable[T] is covariant in T while ReadOnly[T] is invariant.

Note: This approach requires a stronger treatment of typing.Never than is usually done by type checkers: For this to work, we really require that Never is uninhabited and hence type-checkers to error when an instance of Never is created.

1 Like