Thursday, 11 November 2021

Correct way to "downcast" with typehints

I'd like to know what the correct way is to "downcast" types with Python type hints.

Given that B derives from A, in Java/C++/C# we would just downcast A to B like this

 ((B) a1).f2()

I thought I could do the same in Python with typing.cast

from typing import Generic, List, Type, cast, Any
from random import randint

class A: # base class
    def f1(self) -> None:
        print("f1")
class B(A): # derived class
    def f2(self) -> None:
        print("f2")

a1:A = A() # let's say at some point a1 contained an A instance
if randint(1,10) < 11: # pretend I then call a method that I know for sure returns a B instance
    a1 = B()

# a1.f2() # there is no f2() in A, so the IDE complains correctly - need to downcast

temp:Any = a1 # I can use Any to replace downcast
b1:B = temp
b1.f2() # IDE is happy and works OK

# I thought this would work, but does not
b1:B = cast(a1,B) # "B | A" cannot be assigned  "B"
b1.f2()

In python I've gotten it to work using Any, but I'd like to use typing.cast instead.

Using Python 3.8.1 and Visual Code + PyLance



from Correct way to "downcast" with typehints

No comments:

Post a Comment