Skip to content Skip to sidebar Skip to footer

How Do I Type-hint That A Python Function Returns Instance Of Any Class Derived From A Superclass?

I've got a bunch of Django template inclusion tags, which take as an argument either a specific instance of a database object or a string/int, which is interpreted as the primary k

Solution 1:

What you want to do here is make your fetch_object function a generic function.

That is, rather then just saying that your function accepts any Type[Model], capture exactly which kind of model you accept using a type variable, and specify that exact kind is the output. For example:

from typing import TypeVar

# The bound states that T can be bound to Model or any subclass of Model.# If the bound keyword argument is omitted, we assume the bound is 'object'.
T = TypeVar('T', bound=Model)

def fetch_object(cls: Type[T] = None, obj: Union[T, str, int] = None) -> Optional[T]:
    if isinstance(obj, cls):
        return obj
    elif isinstance(obj, str) or isinstance(obj, int):
        try:
            return cls.objects.get(pk=obj)
        except (cls.DoesNotExist, ValueError):
            pass
    return None

One minor note on stylistic conventions: I chose to name the typevar T here for brevity. The other common convention is to name your typevar something like _TModel or _ModelT. That is, the underscore to make the variable private, and a longer name for readability.

Post a Comment for "How Do I Type-hint That A Python Function Returns Instance Of Any Class Derived From A Superclass?"