Replies: 2 comments
-
This isn't allowed for the same reason that setting an undeclared attribute isn't allowed on any other object. For example, this is allowed at runtime, but it's a type violation. class Foo: ...
x = Foo()
x.bar = 42 # Type error If you want pyright to allow accesses to undeclared attributes on a function, you can disable the If you want to do this in a type-safe manner, you would need to define a wrapper class that declares the attributes and their types. Something like this: class CallableWithBar[**P, R]:
bar: dict[str, int] = {}
def __init__(self, func: Callable[P, R]) -> None:
self._func = func
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:
return self._func(*args, **kwargs) |
Beta Was this translation helpful? Give feedback.
-
So far my crude work-around is a Protocol and one def foo(a: int): return a
class Foo(Protocol):
def __call__(self, a: int) -> int: ...
bar: int
foo: Foo = foo # type: ignore After which pyright is happy with attribute access... and even mypy can be coerced (must have separate names for function def and typed variable). P.S. I think what I wanted, ultimately, was to have correct types without runtime overhead. |
Beta Was this translation helpful? Give feedback.
-
MRE
How did I get here, simplified:
Code tested on py3.8 .. 3.13
P.S. I'm not too happy with the (ilelgal?) type hint
inner.bar: SomeType = ...
, but Python allows this at run time.Beta Was this translation helpful? Give feedback.
All reactions