Search code examples
pythonglobal-variablesconstants

In python, how to store 'constants' for functions only once?


Some function need 'constant' values (i.e. not designed to be redefined later) that are not to be parametrized. While default arguments are stored only once for each function, some are just not very meaningful to be put as parameters (i.e. to be part of the signature). For (a not very useful) example:

def foo(bar):
    my_map = {"rab": barType, "oof": fooType}
    return my_map.get(bar,defaultType)()

It wasted CPU time and RAM space to re-define such a constant for each call. Some other ways are to store such constants as module level globals or make the function a callable class, but there may be other ways, maybe?

When doing the module level global way, I prefix my (meant as a) constant variable with a "_" to show that it is there not for anyone's interest. Still I feel the module namespace slightly "polluted", not to speak of the shame of using something as discouraged as globals at all:

_my_map = {"rab": barType, "oof": fooType}
def foo(bar):
    return _my_map.get(bar,defaultType)()

Or the transform it into a class way. I make the __call__ a classmethod, to avoid the need of creating instances:

class foo:
   my_map = {"rab": barType, "oof": fooType}
   @classmethod
   def __call__(cls,bar):
       return cls.my_map.get(bar,defaultType)()

Are these solutions pythonic enough?

Are there other ways to do this?

Is it even ok as a practice to use such 'constants'?

Note these objects in my examples are not necessarily actual constants, but used (and could be thought) as such by their purpose.


Solution

  • Set it as an attribute on the function:

    def foo(bar):
        return foo.my_map.get(bar, defaultType)()
    foo.my_map = {"rab": barType, "oof": fooType}
    

    A callable class or a closure is not simple enough IMO.