Constants In Python (Posting On Python-List Prohibited)

Lawrence D’Oliveiro lawrencedo99 at gmail.com
Sat Nov 18 17:48:26 EST 2017


Every (unqualified) name in Python is a variable. Which means its value can be changed. If you want something that has a value that cannot be changed, you have to make it an attribute of an object. For example, enums work this way. You could define an enum for constants, but enums are nominally opaque to some degree. If you want non-opaque constant definitions, how about this:

    def constants(**kwargs) :
        "defines an object with attributes that are given read-only" \
        " values according to the keyword arguments passed."

        class generator_class :
            "parent class for generating constant-container instance."
            pass
        #end generator_class

        def gen_constitem(name, val) :

            def constitem(self) :
                return \
                    val
            #end constitem

        #begin gen_constitem
            constitem.__name__ = name
            return \
                property(constitem)
        #end gen_constitem

    #begin constants
        for name in kwargs :
            setattr(generator_class, name, gen_constitem(name, kwargs[name]))
        #end for
        return \
            generator_class()
    #end constants

Example use:

    MY_CONSTS = constants \
      (
        apple = "fruit",
        count = 3,
        compound = {"key" : "value"},
      )
    print(MY_CONSTS.apple)
    print(MY_CONSTS.count)
    print(MY_CONSTS.compound)
    MY_CONSTS.apple = 2.0
    print(MY_CONSTS.apple)

produces output:

    fruit
    3
    {'key': 'value'}

    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-22-e46d365e805a> in <module>()
         31 print(MY_CONSTS.count)
         32 print(MY_CONSTS.compound)
    ---> 33 MY_CONSTS.apple = 2.0
         34 print(MY_CONSTS.apple)

    AttributeError: can't set attribute




More information about the Python-list mailing list