I often define variables that will never change, i.e. constants, at the top of a script/module. But recently I've been wondering if it makes sense to define them at the function scope level if they are only used by a single method.
LIST_OF_THINGS = [('a', 1), ('b', 2), ('c', 3)]
def some_op():
for thing in LIST_OF_THINGS:
do_something_with(thing)
While Python has no notion of constants, in this case LIST_OF_THINGS
is never modified and only called by a single method, ever. If LIST_OF_THINGS
was ever modified, it would be a hardcoded modification in a new release. Now while this is a simple case, I recently had the need for a data structure that later references other methods:
LIST_OF_OPS = {'foo': _call_foo, 'bar': _call_bar} # Python throws a fit here
def _call_foo(): pass
def _call_bar(): pass
def some_op():
for op in LIST_OF_OPS:
LIST_OF_OPS[op]()
So I had two options:
- Lower the location of the "constant"' below the referenced methods
- Place the "constant" inside
some_op
Again, a simple case, but when the structure of a constant or the number of constants is large, they can make the body of a function larger than it should be; this is really the only merit I see in having them defined at the function scope level.