[Python] Can I override type of an existing attribute by `__getattribute__` method?

Discussão em 'Python' iniciado por Stack, Junho 17, 2025.

  1. Stack

    Stack Membro Participativo

    I wrote a simple code where I override the __getattribute__ method so that it always returns an empty string. But Pyright doesn't understand this and complains "int" is not assignable to "str"

    My code:

    import typing as ty
    from dataclasses import dataclass


    class MetaModel(type):
    def __new__(cls, name, bases, attrs):
    return super().__new__(cls, name, bases, attrs)

    def __getattribute__(cls, name: str, /) -> str:
    if name.startswith("_"):
    return super().__getattribute__(name)
    return ""


    class BaseModel(metaclass=MetaModel):
    def __getattribute__(self, name: str) -> str:
    return ""


    @dataclass
    class Model(BaseModel):
    field: int = 0


    if __name__ == "__main__":
    model = Model()
    field1: str = model.field # "int" is not assignable to "str"
    field2: str = Model.field # "int" is not assignable to "str"
    field3: str = Model.undefined_field # it`s fine
    ty.reveal_type(field1) # str
    ty.reveal_type(field2) # str
    ty.reveal_type(field3) # str

    Continue reading...

Compartilhe esta Página