Matt
Matt

Reputation: 1632

How do I specify that the return type will be the same as the input type?

I have a function below where target can be any type. I want to type this function so that the output T is the same as whatever type is passed in as target.

from typing import Type, TypeVar

T = TypeVar("T")

def lowercase_if_possible(target: Type[T]) -> T:
    if isinstance(target, str):
        return target.lower()
    return target

I assume this has something to do with generics but I can't figure out the syntax as the Python docs only show generics used on classes, not an individual function.

Upvotes: 2

Views: 1626

Answers (2)

chepner
chepner

Reputation: 531205

Type[T] indicates that the value of target is a class (or subclass) itself, rather than a value of the type. For example,

def instantiate(c: Type[T]) -> T:
    return c()

instantiate(int)  # Returns 0, a value of type int
instantiate(str)  # Returns "", a value of type str

T alone is all you need. Given a value of type T, you'll return a value of type T, regardless of what that type is.

def lowercase_if_possible(target: T) -> T:
    if isinstance(target, str):
        return target.lower()
    return target

(Note that without a runtime check to determine what T actually is, the only think you can do is return the given value, because you don't know enough about the value to actually do anything with it.)

Generics are for defining a class that wraps an arbitrary but definite type.

Upvotes: 2

Guybrush
Guybrush

Reputation: 2780

You're close to the right solution, simply use T as the type for target and it should do the trick.

Upvotes: 1

Related Questions