How to save typed function arguments and pass to function in Python?

Viewed 37

Let's say I define the following function with typed arguments:

from typing import List

def map_names_to_ages(names: List[str], ages: List[int]):
    return { name: ages[index] for index, name in enumerate(names) }

And I have another function with the same arguments:

def generate_sentence(names: List[str], ages: List[int]):
    return [f"{name} is {ages[index]} years old" for index, name in enumerate(names)]

What if I want to define the typed input arguments only once? Can I save and reuse them somehow? Something like this:

args = ...
def map_names_to_ages(args):
    ...
def generate_sentence(args):
    ...
1 Answers
StringList = List[str]
def map_names_to_ages(args: StringList):
    ...
def generate_sentence(args: StringList):
    ...

The types are nothing magical, they are just values like anything else. The only reason StringList starts with a capital here is convention.

EDIT: I might have misunderstood the question, if you want to define the signature of the function only once.

It is semi-possible with decorators:

from typing import Callable, List


def string_list(f: Callable[[List[str], List[int]], None]) -> Callable[[List[str], List[int]], None]:
    def wrapper(names: List[str], ages: List[int]) -> None:
        f(names, ages)
    return wrapper


@string_list
def map_names_to_ages(*args):
    pass


@string_list
def generate_sentence(names, ages):
    pass

@string_list
def generate_sentence(porcupines, stevedores):
    pass

but not a good idea in general because it does obfuscate the signature.

Related