Ekos IV
Ekos IV

Reputation: 367

Using type hints to ensure that two function parameters are of the same type

Say I have a function that retrieves a value from a source, then maps it to another type before returning it.

An example function declaration might look like this:

def get_value(mapping_function: Callable[[str], any]) -> any:
    # ...

The function would retrieve the value from some source and then map it according to the mapping_function before returning the result.

Is there any way I can specify that the returned type and the result of the lambda would be of the same type? It could be any type, but it will always be the same, something like the following:

def get_value(mapping_function: Callable[[str], T]) -> T:
    # ...

For example, in Java, I could do:

public static <T> T getValue(Function<String, T> mappingFunction) {
  // ...
}

Maybe I wrap it in a class with a generic type or something?

Upvotes: 2

Views: 59

Answers (1)

sturgemeister
sturgemeister

Reputation: 456

should be:

from typing import TypeVar

T = TypeVar('T')

def get_value(mapping_function: Callable[[str], T]) -> T:
    # ...

Upvotes: 2

Related Questions