Skip to content
Advertisement

Return type based on type argument

I have this code, which type checks fine on its own:

JavaScript

But if I try to use it:

JavaScript

I get

Incompatible return value type (got “Tuple[BaseObject, …]”, expected “Tuple[DerivedObject, …]”)mypy(error)

I can fix this with

JavaScript

But what I would really like to do is specify that df2objects returns a Tuple of object_type, like this:

JavaScript

or this:

JavaScript

Of course, neither of those actually work.

Advertisement

Answer

As was alluded to in the comments, using a TypeVar is the solution here, I believe. Assuming DerivedObject is a subclass of BaseObject, the following should work:

JavaScript

By using the bound keyword-argument, we restrict the possible types the TypeVar T could be to DerivedObject and its subclasses.

The mypy documentation on generic functions can be found here, the docs for TypeVar can be found here, and information on bound TypeVars can be found here.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement