1

Lets say I have a class like this:

class Colors:
    RED = '\33[31m'
    GREEN = '\33[32m'
    YELLOW = '\33[33m'
    BLUE = '\33[34m'
    ...

How can I loop through these variables without turning them into strings?

eg:

for color in Colors:
    print(color + 'foo') //should print foo in terminal in each color

I attempted to use this question's answer, but this was the result:

colors = [attr for attr in dir(Colors) if not callable(getattr(Colors, attr)) and not attr.startswith("__")]

for color in colors:
    print(color + 'foo')
    //prints this:

    //REDfoo
    //GREENfoo
    ...

I also tried this:

colors = [attr for attr in dir(Colors) if not callable(getattr(Colors, attr)) and not attr.startswith("__")]

for color in colors:
    print(Colors.color + 'foo') //error: Colors has no attribute 'color'   
    print(Colors[color] + 'foo') //error: Colors object is not subscriptable 

Is there any way to make this work that doesn't involve copy/pasting each color?

this is where I found the colors.

Lord Elrond
  • 13,430
  • 7
  • 40
  • 80
  • why do you need a class here? Is there other functionality you need which you haven't shared here? With what you have told us, it seems like this should just be a simple dictionary, not a class at all. – Robin Zigmond Feb 20 '19 at 00:14
  • You should use an enum, then you can iterat directly over th class – juanpa.arrivillaga Feb 20 '19 at 01:38

1 Answers1

3

The dir function returns a list of attribute names of the given object. You should then use the getattr function to obtain the value of an attribute by name instead:

colors = [getattr(Colors, attr) for attr in dir(Colors) if not callable(getattr(Colors, attr)) and not attr.startswith("__")]

or as @juanpa.arrivillaga suggested in the comment, you can use the vars function instead to avoid having to call getattr to obtain attribute values:

colors = [value for attr, value in vars(Colors).items() if not callable(value) and not attr.startswith("__")]
blhsing
  • 91,368
  • 6
  • 71
  • 106