Weiner Nir
Weiner Nir

Reputation: 1475

Loop over all variables in class that acts like enum

I have a class that acts like an enum. I want to loop over his variables (enum's values)

class Demos(object):
    class DemoType(object):
        def __init__(self, name):
            self.name = name

        def __repr__(self):
            return self.name

    VARIABLE1 = DemoType("Car")
    VARIABLE2 = DemoType("Bus")
    VARIABLE3 = DemoType("Example")
    VARIABLE4 = DemoType("Example2")

I thought about using Role.__dict__, or vars(Role), but they contain not only the variables, but also the RoleType class and other attributes like __module__. __doc__ and more...

I also want it to be represented like this, mainly because it will add more variables to DemoType. variables other than name, So please try to find an answer this way.

Upvotes: 2

Views: 3547

Answers (2)

Weiner Nir
Weiner Nir

Reputation: 1475

I found the answer, And its not a duplicate of How can I represent an 'Enum' in Python? at all. The answer is to create the following list by the following list comprehensive:

variables = [attr for attr in dir(Demos()) if not attr.startswith("__") and not callable(attr)]
print variables 

I can also create a function to do that for me this way:

class Demos(object):
    class DemoType(object):
        def __init__(self, name):
            self.name = name

        def __repr__(self):
            return self.name

    @classmethod
    def get_variables(cls):
        return [getattr(cls, attr) for attr in dir(cls) if not callable(getattr(cls, attr)) and not attr.startswith("__")]

    VARIABLE1 = DemoType("Car")
    VARIABLE2 = DemoType("Bus")
    VARIABLE3 = DemoType("Example")
    VARIABLE4 = DemoType("Example2")


for variable in Demos.get_variables():
    print variable

Upvotes: 0

Ethan Furman
Ethan Furman

Reputation: 69051

Rather than reinvent an enum type, it would be better to use Python's Enum type (which has also been backported). Then your code could look like

class Demos(Enum):
    VARIABLE1 = "Car"
    VARIABLE2 = "Bus"
    VARIABLE3 = "Example"
    VARIABLE4 = "Example2"


--> for variable in Demos:
...    print variable

Upvotes: 1

Related Questions