Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism and Type Hints in Python

Consider the following case:

class Base:
    ...

class Sub(Base):
    ...

def get_base_instance(*args) -> Base:
    ...

def do_something_with_sub(instance: Sub):
    ...

Let's say I'm calling get_base_instance in a context where I kow it will return a Sub instance - maybe based on what args I'm passing. Now I want to pass the returned instance to do_something_with_sub:

sub_instance = get_base_instance(*args)
do_something_with_sub(sub_instance)

The problem is that my IDE complains about passing a Base instance to a method that only accepts a Sub instance.

I think I remember from other programming languages that I would just cast the returned instance to Sub. How do I solve the problem in Python? Conditionally throw an exception based on the return type, or is there a better way?

like image 403
Tobias Feil Avatar asked Jul 02 '26 13:07

Tobias Feil


1 Answers

I think you were on the right track when you thought about it in terms of casting. We could use cast from typing to stop the IDE complaining. For example:

from typing import cast


class Base:
    pass


class Sub(Base):
    pass


def get_base_instance(*args) -> Base:
    return Sub()


def do_something_with_sub(instance: Sub):
    print(instance)


sub_instance = cast(Sub, get_base_instance())
do_something_with_sub(sub_instance)
like image 198
Richard Ambler Avatar answered Jul 04 '26 01:07

Richard Ambler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!