Skip to content

Instantly share code, notes, and snippets.

@sirkonst
Last active May 26, 2016 13:06
Show Gist options
  • Save sirkonst/6387107 to your computer and use it in GitHub Desktop.
Save sirkonst/6387107 to your computer and use it in GitHub Desktop.
Easy define python constants type.
class Constants(type):
class _ConstantsBase(dict):
def __getattribute__(self, name):
try:
return self[name]
except LookupError:
raise AttributeError(name)
def __contains__(self, name):
return name in dict.values(self)
def __new__(mcs, name, bases, dct):
d = {}
for k, v in dct.items():
if not k.startswith("_"):
d[k] = v
return type(name, (Constants._ConstantsBase,), dct)(d)
class COLOR_TYPES(object):
__metaclass__ = Constants
RED = "red"
GREEN = "green"
BLUE = "blue"
if __name__ == "__main__":
print COLOR_TYPES
# >> {'BLUE': 'blue', 'GREEN': 'green', 'RED': 'red'}
print COLOR_TYPES.RED
# >> red
print "red" in COLOR_TYPES
# >> True
print "yellow" in COLOR_TYPES
# >> False
@sirkonst
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment