1

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 
4
  • No Pyright on Pi5 debian bookworm, but I have the same errors with mypy (version 1.0.1). Visibly both do not manage/see the override Commented Jun 17 at 6:21
  • Possibly ask at github.com/microsoft/pyright directly. Commented Jun 17 at 7:45
  • You can't, this is by design. Any statically typed attributes retain their types even in presence of __getattr{,ibute}__. Commented Jun 17 at 13:01
  • Unfortunately, static type checkers at this point don't look at overridden special methods which change class behavior. I don't know if you can workaround this, but the suggestion is to file bugs about your type-checker tools of interest: after all, the modified behavior is not dynamic and is previsible, in this case, and therefore static type checkers are in error. Commented Jun 19 at 22:41

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.