Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all constants within a class in python

I have a class which is essentially used to define common constants for other classes. It looks something like the following:

class CommonNames(object):
    C1 = 'c1'
    C2 = 'c2'
    C3 = 'c3'

And I want to get all of the constant values "pythonically". If I used CommonNames.__dict__.values() I get those values ('c1', etc.) but I get other things such as:

<attribute '__dict__' of 'CommonNames' objects>,
<attribute '__weakref__' of 'CommonNames' objects>,
None ...

Which I don't want.

I want to be able to grab all the values because this code will be changed later and I want other places to know about those changes.

like image 466
sedavidw Avatar asked Feb 19 '15 21:02

sedavidw


People also ask

How do you find constants in Python?

In Python, constants are usually declared and assigned in a module. Here, the module is a new file containing variables, functions, etc which is imported to the main file. Inside the module, constants are written in all capital letters and underscores separating the words.

How do you show all class variables in Python?

The variables that are defined outside the class can be accessed by any class or any methods in the class by just writing the variable name.

Does Python have consts?

In programming, the term constant refers to names representing values that don't change during a program's execution. Constants are a fundamental concept in programming, and Python developers use them in many cases.


2 Answers

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]
like image 157
Martijn Pieters Avatar answered Oct 12 '22 12:10

Martijn Pieters


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('_')]
like image 30
galgertz Avatar answered Oct 12 '22 11:10

galgertz