'How to type a generic function with namedtuples?

I have a wrapper class for a database cursor like this:

namedtuple_def = TypeVar("namedtuple_def")

class Wrapper:
    def fetchall(defn: Optional[namedtuple_def] = None) -> List[namedtuple_def]:
        return self.cursor.fetchall()

The underlying cursor always returns namedtuples, but the nametuple returned depends on the query run. So I'm trying to get it to take a nametuple type as an unused parameter to hint exactly what types are getting returned. If you call it without the defn parameter the return type is partially erased, but if you pass the equivalent namedtuple class your query results have fully specified types.

My problem with the code above is that the typechecker thinks I'm returning the type variable/class for the namedtuple argument, not the instantiated namedtuples - or in other words, List[Type[my_namedtuple]] instead of List[my_namedtuple]. How do I fix the type signature?

n.b. I am using the PyCharm typechecker, not MyPy, but I don't expect them to vary here.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source