Skip to content

Instantly share code, notes, and snippets.

@wolfg1969
Created July 28, 2014 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolfg1969/0b1e53c7862489fef92e to your computer and use it in GitHub Desktop.
Save wolfg1969/0b1e53c7862489fef92e to your computer and use it in GitHub Desktop.
Constants in Python
# 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