Consider the following case:
JavaScript
x
12
12
1
class Base:
2
3
4
class Sub(Base):
5
6
7
def get_base_instance(*args) -> Base:
8
9
10
def do_something_with_sub(instance: Sub):
11
12
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
:
JavaScript
1
3
1
sub_instance = get_base_instance(*args)
2
do_something_with_sub(sub_instance)
3
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?
Advertisement
Answer
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:
JavaScript
1
22
22
1
from typing import cast
2
3
4
class Base:
5
pass
6
7
8
class Sub(Base):
9
pass
10
11
12
def get_base_instance(*args) -> Base:
13
return Sub()
14
15
16
def do_something_with_sub(instance: Sub):
17
print(instance)
18
19
20
sub_instance = cast(Sub, get_base_instance())
21
do_something_with_sub(sub_instance)
22