Created
July 28, 2014 11:42
-
-
Save wolfg1969/0b1e53c7862489fef92e to your computer and use it in GitHub Desktop.
Constants in Python
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
# http://code.activestate.com/recipes/65207-constants-in-python/?in=user-97991 | |
class _const(object): | |
class ConstError(TypeError): | |
pass | |
class ConstCaseError(ConstError): | |
pass | |
def __setattr__(self, name, value): | |
if name in self.__dict__: | |
raise self.ConstError, "Can't rebind const({0})".format(name) | |
if not name.isupper(): | |
raise self.ConstCaseError, 'const name {0} is not all uppercase'.format(name) | |
self.__dict__[name] = value | |
import sys | |
# http://stackoverflow.com/questions/5365562/why-is-the-value-of-name-changing-after-assignment-to-sys-modules-name | |
# ref = sys.modules['__main__'] | |
sys.modules[__name__] = _const() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment