Eliav Louski
Eliav Louski

Reputation: 5224

How to define a type for a function (arguments and return type) with a predefined type?

I want to define a function signature (arguments and return type) based on a predefined type.

Let's say I have this type:

safeSyntaxReadType = Callable[[tk.Tk, Notebook, str], Optional[dict]]

which means safeSyntaxReadType is a function that receives 3 arguments (from types as listed above), and it can return a dict or may not return anything.

Now let's say I use a function safeReadJsonFile whose signature is:

def safeReadJsonFile(root = None, notebook = None, path = ''):

I want to assign the type safeSyntaxReadType to the function safeReadJsonFile in the signature, maybe something like:

def safeReadJsonFile:safeSyntaxReadType(root = None, notebook = None, path = ''):

But this syntax doesn't work. What is the right syntax for such type assigning?

I can do it this way:

def safeReadJsonFile(root:tk.Tk = None, notebook:Notebook = None, path:str = '') -> Optional[dict]:

but I want to avoid that.

After reading a lot (all the typing docs, and some of PEP544), I found that there is no such syntax for easily assigning a type to a whole function at the definition (the closest is @typing.overload and it's not exactly what we need here).

But as a possible workaround I implemented a decorator function which can help with easily assigning a type:

def func_type(function_type):
    def decorator(function):
        def typed_function(*args, **kwargs):
            return function(*args, **kwargs)
        typed_function: function_type  # type assign
        return typed_function
    return decorator

The usage is:

greet_person_type = Callable[[str, int], str]

def greet_person(name, age):
    return "Hello, " + name + " !\nYou're " + str(age) + " years old!"

greet_person = func_type(greet_person_type)(greet_person)
greet_person(10, 10) # WHALA! typeerror as expected in `name`: Expected type 'str', got 'int' instead

Now, I need help: for some reason, the typechecker (pycharm) doesn't hint the typing if use decorated syntax which supposed to be equilavent:

@func_type(greet_person_type)
def greet_person(name, age):
    return "Hello, " + name + " !\nYou're " + str(age) + " years old!"

greet_person(10, 10)  # no type error. why?

I think the decorated style does not work because decoration does not change the original function greet_person so the typing from the returned decorated function doesn't affect when inting the original greet_person function.

How can I make the decorated solution work?

Upvotes: 10

Views: 3213

Answers (1)

MisterMiyagi
MisterMiyagi

Reputation: 50076

Simply assign the function to a new name representing the specific callable type.

Greetable = Callable[[str, int], str]

def any_greet_person(name, age):
    ...

typed_greet_person: Greetable = any_greet_person

reveal_type(any_greet_person)
reveal_type(typed_greet_person)

Keep in mind that the object defined as any_greet_person is of a specific type, which you cannot simply erase after creating it.


In order to create the callable with a specific type, one can copy it from a template object (the abstract types Callable and Protocol do not work with Type[C]). This can be done with a decorator:

from typing import TypeVar, Callable

C = TypeVar('C', bound=Callable)  # parameterize over all callables

def copy_signature(template: C) -> Callable[[C], C]:
    """Decorator to copy the static signature between functions"""
    def apply_signature(target: C) -> C:
        # copy runtime inspectable metadata as well
        target.__annotations__ = template.__annotations__
        return target
    return apply_signature

This also encodes that only functions compatible with the copied signature are valid targets.

# signature template
def greetable(name: str, age: int) -> str: ...

@copy_signature(greetable)
def any_greet_person(name, age): ...

@copy_signature(greetable)  # error: Argument 1 has incompatible type ...
def not_greet_person(age, bar): ...

print(any_greet_person.__annotations__)  # {'name': <class 'str'>, 'age': <class 'int'>, 'return': <class 'str'>}
if TYPE_CHECKING:
    reveal_type(any_greet_person) # note: Revealed type is 'def (name: builtins.str, age: builtins.int) -> builtins.str'

Upvotes: 8

Related Questions