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?