C-style static variables in Python?

kj no.email at please.post
Fri Apr 2 18:08:42 CEST 2010

In <mailman.1437.1270163476.23598.python-list at python.org> Steve Holden <steve at holdenweb.com> writes:

>But the real problem is that the OP is insisting on using purely
>procedural Python when the problem is screaming for an object-oriented

My initial reaction to this comment was something like "What? switch
from procedural to OO just to be able to do some one-time initialization
of function-private data???"  But then, again, since Python allows
easy mixing of both programming styles, I suppose one could refactor this:

def spam(x, y, z):
        mongo = spam.mongo
    except AttributeError:
        mongo = spam.mongo = heavy_lifting_at_runtime()
    return frobnicate(x, y, z, mongo)

ham = spam(3, 4, 5)

into this:

class _Spam(object):
    def _(cls, x, y, z):
            mongo = cls.mongo
        except AttributeError:
            mongo = cls.mongo = heavy_lifting_at_runtime()
        return frobnicate(x, y, z, mongo)

ham = _Spam._(1, 2, 3)

Is this really more natural or more readable?  Hmmm.

In any case, the first solution does rely on the fact that functions
are objects, and therefore can have attributes, so even the
"procedural" version relies on Python's OO model.

Other responses advocated for global variables.  I avoid them in
general, and doubly so in Python, because I find Python's shenanigans
with globals mystifying (this business of becoming silently local
if assigned to); it's one rare instance in which Python out-Perls
Perl.  And yes, I know that the language includes ways to deal with
this (with the global keyword, etc.) but I find the whole scheme
is so much "cutting against the grain".

Thanks for all the replies.  There are a lot of good ideas there.
I'm particular, I'm thankful for the pointers to PEP 3130 (initial
reaction: maybe I should learn Dutch) and to functools.wraps, and
for the code snippets.


More information about the Python-list mailing list