Search code examples
pythonvisual-studio-codetype-safety

How can you write almost type safe code having a list of objects within a class?


I am looking for a way to write almost type safe / maintainable code in Python while using a list of objects. I have found the following way of enforcing intellisense functionality (tested in vscode):

class MyObject(object):
    key1 = None
    key2 = None

a = MyObject()

v = []


def add_element():
    a = MyObject()
    a.key1 = 1
    v.append(a)

add_element()

# this works (intellisense)
print(v[0].key1)

However, when used inside a class, the same idea does not work anymore (with regards to intellisense):

class MyClass():
    v = []

    def add_element(self):
        a = MyObject()
        a.key1 = 1
        self.v.append(a)

    def use_element(self):
        # this does not show (intellisense)
        print(self.v[0].key1)


c = MyClass()

c.add_element()
c.use_element()

I'm guessing there should be a simple fix for this.


Solution

  • As pointed out in the comments, you need to make v an instance attribute:

    class MyClass:
    
        def __init__(self):
            self.v = []
    
        def add_element(self):
            a = MyObject()
            a.key1 = 1
            self.v.append(a)
    
        def use_element(self):
            # this does not show (intellisense)
            print(self.v[0].key1)
    

    But you said type-safe, which means you should also add type annotations and run mypy on your code to make sure all the code is using your expected types appropriately.

    from typing import List
    
    class MyClass:
    
        def __init__(self) -> None:
            self.v: List[MyObject] = []
    
        def add_element(self) -> None:
            a = MyObject()
            a.key1 = 1
            self.v.append(a)
    
        def use_element(self) -> None:
            # this does not show (intellisense)
            print(self.v[0].key1)