2

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?

2
  • It looks like you already have your answer. Commented Jun 17, 2021 at 22:09
  • 1
    This is discussed in the typing module's documentation on Generics. Commented Jun 17, 2021 at 22:09

1 Answer 1

2

should be:

from typing import TypeVar

T = TypeVar('T')

def get_value(mapping_function: Callable[[str], T]) -> T:
    # ...
Sign up to request clarification or add additional context in comments.

1 Comment

positional arguments will constrain the type from Any to some list: T = TypeVar('T', int, float, complex)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.