Lesser evil hack? (static data)

D. Michael McFarland mcfarlan at lomond.caber-eng.com
Thu May 27 10:30:41 EDT 1999


I've followed the "how to imitate a C static variable" thread with
some interest, and now feel compelled to float my attempt at it for
"review".  I don't think it's an evil hack, but it is at least
borderline obfuscated.

A little background: In a program I'm playing with, a few functions
are called many times with the same arguments, or with arguments from
a small set.  In the interest of efficiency, I'd like to compute the
return value corresponding to a given argument only once, storing it
somewhere "static" so I can look it up rather than recompute it the
next time the same function is called with the same argument(s).  For
reasons of laziness, er, elegance, I want this to be transparent to
the calling code.  This may or may not be a win in terms of run time,
but at some point it became personal, and the following is the result:

class PersistentData:
    """Dummy name space for data that should persist between function calls."""
    pass

def GaussPointsAndWeights(order):
    """Return Gauss integration points (in [-1, 1]) and weights."""
    try:                                # See if dictionary exists.
        d = PersistentData.GaussPointsAndWeights_dict
    except:                             # If not, create it.
        d = PersistentData.GaussPointsAndWeights_dict = {}
    if d.has_key(order):                # We've done this before.
        return d[order]
    else:                               # Create return value from scratch.
        if order == 2:
            ...
        elif order == 4:
            ...
        ...                             # Create pairs (a list of tuples),
                                        # possibly at great expense.
        d[order] = pairs
        return pairs

On the first call of GaussPointsAndWeights(order) with order = 2, say,
the dictionary PersistentData.GaussPointsAndWeights_dict is created
and the return value stored with key 2; subsequent calls with order =
2 lead to a look-up rather than the construction of the return value
from scratch.  The first call with order = 4 adds a key, value pair to
the diciontary, and so forth.  Other functions that want to do the
same sort of thing can create their own dictionaries (or scalars,
lists, etc.) in the name space of the PersistentData class.

So, my questions are:

1.  How bad is this?  Should I hide it from my Mom?

2.  Am I missing a better mechanism for doing the same thing?

Looking forward to your feedback, I think,
Michael
--
    D. Michael McFarland   <mcfarlan at caber-eng.com>
    Caber Engineering, Inc., Glastonbury, Connecticut




More information about the Python-list mailing list