Understanding Type Hinting with Python Arrays (Lists)

I believe I understand that when defining an empty array (list), you need to type hint it.

This does not work:

class test:
    def __init__(self):
        self.a = randint(0, 10)

l = []

for i in range(4):
    l.append(test())
    pass

for value in l:
    print(value.a) #Line 12: unknown object type; cannot lookup attribute 'a'

This works:

class test:
    def __init__(self):
        self.a = randint(0, 10)

l: List[test] = []

for i in range(4):
    l.append(test())
    pass

for value in l:
    print(value.a)

When introducing a typed list in a class, it throws a strange error:

class pest:
    def __init__(self):
        self.l: List[test] = []  #Line 3: ';' expected.
        for i in range(4):
            self.l.append(test())
            pass

class test:
    def __init__(self):
        self.a = randint(0, 10)

pest_obj = pest()

for value in pest_obj.l:
    print(value.a)

Why is that?

If I "seed’ the list with a value on definition, the compiler does not complain:

class pest:
    def __init__(self):
        self.l = [test()]
        for i in range(4):
            self.l.append(test())
            pass

class test:
    def __init__(self):
        self.a = randint(0, 10)

pest_obj = pest()

for value in pest_obj.l:
    print(value.a)

Thanks for the feedback,

Mike

ah, this is definitely a makecode bug (or i guess a python feature we never implemented). we don’t currently have support for annotated assignments on class properties

i’ll file an issue for this. unfortunately, i don’t have a workaround for you right now other than the seeding option you demonstrated

2 Likes

Thanks Richard!