-
Hi. I'm trying to write a decorator for my functions that gets the function result type as its input, and then returns only the required attribute. Something similar to this idea, look at the Params = ParamSpec("Params")
T = TypeVar("T")
def dedecorator(key: str):
def decorator(func: Callable[Params, T]) -> Callable[Params, Attribute[T, key]]:
def wrapper(*args: Params.args, **kwargs: Params.kwargs) -> Attribute[T, key]:
return getattr(func(*args, **kwargs), key)
return wrapper
return decorator Is something possible in Python as of now? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
No, that's not possible in the type system today. If there's a specific attribute that you're interested in, you could define a generic protocol class, like this: Code sample in pyright playground from typing import Callable, Protocol
class SupportsFoo[T](Protocol):
""" Structural type for a class that supports a read/write "foo" parameter """
foo: T
def decorator[**Params, T](func: Callable[Params, SupportsFoo[T]]) -> Callable[Params, T]:
def wrapper(*args: Params.args, **kwargs: Params.kwargs) -> T:
return getattr(func(*args, **kwargs), 'foo')
return wrapper
class FooImpl:
foo: int
@decorator
def func() -> FooImpl:
... |
Beta Was this translation helpful? Give feedback.
-
There is also a mypy plugin that may help you get there https://pypi.org/project/mypy-extras/ which has an |
Beta Was this translation helpful? Give feedback.
No, that's not possible in the type system today. If there's a specific attribute that you're interested in, you could define a generic protocol class, like this:
Code sample in pyright playground