1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] How to annotate return type for a Python function returning a class defined within...

Discussão em 'Python' iniciado por Stack, Outubro 8, 2024.

  1. Stack

    Stack Membro Participativo

    Suppose I have a decorator defined using a callable class as a wrapper. For example:

    from functools import wraps
    from typing import Any, Callable, cast

    def decorator(*args: Any, **kwargs: Any) -> Any:
    class Wrapper:
    def __init__(self) -> None:
    self.args = args
    self.kwargs = kwargs

    def __call__(self, func: Callable[..., Any]) -> Callable[..., Any]:
    @wraps(func)
    def wrapper(*args: Any, **kwargs: Any) -> Any:
    return func(*args, **kwargs)

    return wrapper

    return Wrapper()


    How to properly annotate type its return type?

    So far, I found that the following inheritance "trick" works as I expect:

    from functools import wraps
    from typing import Any, Callable, cast

    class BaseWrapper:
    def __call__(self, func: Callable[..., Any]) -> Callable[..., Any]:
    @wraps(func)
    def wrapper(*args: Any, **kwargs: Any) -> Any:
    return func(*args, **kwargs)

    return wrapper


    def decorator(*args: Any, **kwargs: Any) -> BaseWrapper:
    class Wrapper(BaseWrapper):
    def __init__(self) -> None:
    self.args = args
    self.kwargs = kwargs

    return Wrapper()


    But is there any other way? I just don't want to have the BaseWrapper in the module's namespace.

    Continue reading...

Compartilhe esta Página