Last active
May 26, 2016 13:06
-
-
Save sirkonst/6387107 to your computer and use it in GitHub Desktop.
Easy define python constants type.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also https://docs.python.org/3/library/enum.html