Search code examples
pythonclasstypecasting-operator

How to use an object's type in python?


I'm wanting to go through a list of objects so that my PyCharm IDE knows what type each list item is:

For example, say I know that each item in a list is an class instance of type 'myClass' - how do I use this to cast my objects so that my ide can help with code completion?

for i in range(len(myList)):
    myClass(myList[i]).myClassProperty .....

I know how to do it in Delphi (something like the above) but not in python.

Thanks


Solution

  • In PyCharm, you can use Type Hinting:

    class Bar:
        def __init__(self,bar):
            self.bar = bar
    
        def do_bar(self):
            return self.bar
    
    def foo(x):
        for el in x: # type: Bar
            el.do_bar()
    
    bars = [Bar('hello'), Bar('World')]
    
    foo(bars)
    

    enter image description here