C-style static variables in Python?

kj no.email at please.post
Fri Apr 2 12:08:42 EDT 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
>answer.

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:

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

ham = spam(3, 4, 5)
</procedural>

into this:

<OO>
class _Spam(object):
    @classmethod
    def _(cls, x, y, z):
        try:
            mongo = cls.mongo
        except AttributeError:
            mongo = cls.mongo = heavy_lifting_at_runtime()
        return frobnicate(x, y, z, mongo)

ham = _Spam._(1, 2, 3)
</OO>


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.

~K



More information about the Python-list mailing list