Created
December 23, 2014 08:19
-
-
Save ashwin/e3844158e3d7afd16adb to your computer and use it in GitHub Desktop.
Alex Martelli's recipe to define constant 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
# Helps define a constant in Python | |
# From Section 6.3: Defining Constants | |
# Python Cookbook (2 Ed) by Alex Martelli et al. | |
# | |
# Usage: | |
# import const | |
# const.magic = 23 # First binding is fine | |
# const.magic = 88 # Second binding raises const.ConstError | |
class _const: | |
class ConstError(TypeError): | |
pass | |
def __setattr__(self,name,value): | |
if self.__dict__.has_key(name): | |
raise self.ConstError, "Can't rebind const(%s)" % name | |
self.__dict__[name] = value | |
import sys | |
sys.modules[__name__] = _const() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And for Python 3: