-
Hi, is it possible to overload getattr() from typing import Any
from typing import overload
from typing import Literal
class Obj:
@overload
def __getattr__(self, name: Literal["foo"]) -> int: ...
@overload
def __getattr__(self, name: Literal["bar"]) -> str: ...
def __getattr__(self, name: str) -> Any:
if name == 'foo':
return 1
return '1'
a = Obj()
b = a.foo
c = a.bar
b = getattr(a, 'foo')
c = getattr(a, 'bar') so obviously foo and bar is not recognized by pyright as Literal, but i have no idea what i could use otherwise. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
When pyright evaluates I'll point out that this doesn't work in mypy, which complains that the signature for the |
Beta Was this translation helpful? Give feedback.
-
Seems there is an issue on the mypy tracker, for reference: python/mypy#11142 I found another workaround for my use case, so i don’t need this right now. |
Beta Was this translation helpful? Give feedback.
When pyright evaluates
__getattr__
, it assumes that thename
is of typestr
. It doesn't create a literal type for the member name. I think it's reasonable to support this. It's a relatively minor change.I'll point out that this doesn't work in mypy, which complains that the signature for the
__getattr__
overload is incorrect.