Getting all constants within a class in python
If you're trying to use Martijn example in python3, you should use items() instead of iteritmes(), since it's deprecated
[value for name, value in vars(CommonNames).items() if not name.startswith('_')]
You'll have to filter those out explicitly by filtering on names:
[value for name, value in vars(CommonNames).iteritems() if not name.startswith('_')]
This produces a list of values for any name not starting with an underscore:
>>> class CommonNames(object):
... C1 = 'c1'
... C2 = 'c2'
... C3 = 'c3'
...
>>> [value for name, value in vars(CommonNames).iteritems() if not name.startswith('_')]
['c3', 'c2', 'c1']
For enumerations like these, you'd be better of using the enum34
backport of the new enum
library added to Python 3.4:
from enum import Enum
class CommonNames(Enum):
C1 = 'c1'
C2 = 'c2'
C3 = 'c3'
values = [e.value for e in CommonNames]