danield
danield

Reputation: 325

How can I explicitly specify a class type for a Python variable?

I am fairly new to Python, coming from a Java background. I have something like this:

class A:
    def __init__(self):
        self.var1 = 1
        self.var2 = 2

class B:
    def __init__(self):
        self.my_list = []

    def add(self, a_object):
        self.my_list.append(a_object)

    def show(self):
        for a_object in self.my_list:
            print(a_object.var1, a_object.var2)

Now, I know this code will run but my question is if there is any way to specify in the show method that the a_object variable is actually an object of type A (like a type casting - something that I would write in java like (A)a_object). I would want this firstly for a better readeability of the code and also for autocompletion. I would guess that another solution would be to type the list, which I am also curios if it is possible.

Thank you.

Upvotes: 0

Views: 2032

Answers (1)

crissal
crissal

Reputation: 2647

You can use type hinting. Note, however, that this is not enforced, but guides you - and the IDE - into knowing if you're passing correct arguments or not.

If you're interested in static typing, you can also check mypy.

from typing import List


class A:
    def __init__(self):
        self.var1 = 1
        self.var2 = 2

class B:
    def __init__(self):
        self.my_list: List[A] = []

    def add(self, a_object: A):
        self.my_list.append(a_object)

    def show(self):
        for a_object in self.my_list:
            print(a_object.var1, a_object.var2)

Upvotes: 5

Related Questions