Last active
February 6, 2018 06:52
-
-
Save Svtter/c96e3259e264621e8bc1ab45b4c2675a to your computer and use it in GitHub Desktop.
python const from: http://code.activestate.com/recipes/65207-constants-in-python/?in=user-97991
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
# Put in const.py...: | |
# python2 | |
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() | |
# that's all -- now any client-code can | |
import const | |
# and bind an attribute ONCE: | |
const.magic = 23 | |
# but NOT re-bind it: | |
const.magic = 88 # raises const.ConstError | |
# you may also want to add the obvious __delattr__ |
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# File : const.py | |
# Author : Svtter <[email protected]> | |
# Date : 06.02.2018 | |
# Last Modified Date: 06.02.2018 | |
# Last Modified By : Svtter <[email protected]> | |
class _const: | |
class ConstError(TypeError): | |
pass | |
def __setattr__(self, name, value): | |
if name in self.__dict__: | |
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