Skip to content

Making a decorator which preserves function signature #1927

Closed
@sharmaeklavya2

Description

@sharmaeklavya2

Currently this is how I annotate decorators which don't modify the function signature:

from typing import Any, Callable, TypeVar

FuncT = TypeVar('FuncT', bound=Callable[..., Any])

def print_on_call(func: FuncT) -> FuncT:
    def wrapped(*args, **kwargs):
        print("Running", func.__name__)
        return func(*args, **kwargs)
    return wrapped # type: ignore

I have to use the # type: ignore otherwise I get this error:

decorator.py: note: In function "print_on_call":
decorator.py:9: error: Incompatible return value type (got Callable[[Any, Any], Any], expected "FuncT")

I'm wondering if there is a better way to do this which doesn't need the type: ignore. What do you all suggest?

Maybe mypy can figure out from (*args, **kwargs) that the parameter types are the same. Maybe it can also see that the return value of func is the return value of wrapped so the return type is the same, and hence the function signatures are the same.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions