Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I type cast a non-primitive, custom class in Python?

How can I cast a var into a CustomClass?

In Python, I can use float(var), int(var) and str(var) to cast a variable into primitive data types but I can't use CustomClass(var) to cast a variable into a CustomClass unless I have a constructor for that variable type.

Example with inheritance.

class CustomBase:
    pass

class CustomClass(CustomBase):
    def foo():
        pass

def bar(var: CustomBase):
    if isinstance(var, CustomClass):
        # customClass = CustomClass(var)   <-- Would like to cast here...
        # customClass.foo()                <-- to make it clear that I can call foo here.
like image 259
lachy Avatar asked Dec 02 '25 09:12

lachy


1 Answers

In the process of writing this question I believe I've found a solution.

Python is using Duck-typing

Therefore it is not necessary to cast before calling a function.

Ie. the following is functionally fine.

def bar(var):
    if isinstance(var, CustomClass):
        customClass.foo()

I actually wanted static type casting on variables

I want this so that I can continue to get all the lovely benefits of the typing PEP in my IDE such as checking function input types, warnings for non-existant class methods, autocompleting methods, etc.

For this I believe re-typing (not sure if this is the correct term) is a suitable solution:

class CustomBase:
    pass

class CustomClass(CustomBase):
    def foo():
        pass

def bar(var: CustomBase):
    if isinstance(var, CustomClass):
        customClass: CustomClass = var
        customClass.foo()  # Now my IDE doesn't report this method call as a warning.

like image 51
lachy Avatar answered Dec 04 '25 00:12

lachy



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!