Skip to content

Instantly share code, notes, and snippets.

@ashwin
Created December 23, 2014 08:19
Show Gist options
  • Save ashwin/e3844158e3d7afd16adb to your computer and use it in GitHub Desktop.
Save ashwin/e3844158e3d7afd16adb to your computer and use it in GitHub Desktop.
Alex Martelli's recipe to define constant in Python
# 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()
@Armag67
Copy link

Armag67 commented Oct 27, 2022

And for Python 3:

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