Assigning list comprehension to an enum value

Viewed 78

While preparing some enums & pydantic models for a aws cdk project, I wondered why PyCharm has an issue with me assigning a list comprehensions like the one below to an enum value.

class foo(Enum):
    bar = [str(v * 1024) for v in range(1, 3)]

PyCharm tells me: Expected type 'int', got 'foo' instead. I don't quite understand the issue here, since the code actually runs just fine and spits out the expected result, which is ["512", "1024", "2048"].

Yes, I could just build the list as a normal variable and reference it as the enum value, but I like avoid unnecessary variable declarations when coding.

Is it just not meant to be assigned like this or am I doing something wrong?

EDIT: for clarification: PyCharms TypeChecker marks the v in str(v * 1024) as a warning (yellow line, not red). There is NO ISSUE running the code!

EDIT2: I'm specifically looking to create the cpu/memory-table shown at the bottom of this as a python enum.

1 Answers

This is a way to create dynamic enums

import enum
es = {}
for v in range(1, 3):
    es['n' + str(v * 1024)] = int(v * 1024)
foo  = enum.Enum('foo', es)
print(list(foo)) # this creates a dynamic enum

print enter image description here

you can also access it via

print(foo.n1024) # input
foo.n1024; #ouptut
Related