Search code examples
pythontyping

Specify generic type based on constructor signature


I have a function that takes a generic argument used for type-casting purposes (I know Python doesn't do those but humor me here). Essentially, this function can accept any type that has a constructor which can accept self alone. I want to do something like this:

T = TypeVar("T")  # Annotation here

def some_func(x: Type[T]) -> T:
    return x(do_something_else())

Obviously, this is an over-simplified example, but I'm not sure how to specify the type here. x could be str, int, a class type or anything else.

If I were to annotate x with Callable[[Any], T] then I couldn't submit int or str as arguments because these aren't technically callables, they're types. However, if I submit Type[T] as an argument then mypy will complain that there are too many arguments for object, as described in this GitHub issue.

So, how do I annotate based on the signature of a type's __init__ method?


Solution

  • As it turns out, my assertion that I couldn't annotate with Callable[[Any], T] was incorrect because str and int do qualify for this annotation:

    def some_func(x: Callable[[Any], T]) -> T:
        return x(do_something_else())