Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to define constant in Python

📅 2014-Dec-23 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ constant, python ⬩ 📚 Archive

Due to the design and dynamic typing of Python, there is no inherent type qualifier that is equivalent to the const of C or C++. I like the solution provided in Section 6.2 (Defining Constants) of the book Python Cookbook (2 Ed) by Alex Martelli et al.

# 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()

Tried with: Python 2.7.6 and Ubuntu 14.04


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧