Static Variables

Andrew Dalke dalke at dalkescientific.com
Wed Apr 3 01:29:48 EST 2002


David Mertz:
>From the other responses, it seems like a lot of users don't know the
>"Python static trick."  I use this moderately often... it is a slightly
>strange spelling, but not hard once you learn it:
>
>    >>> def counter(msg, cnt=[0]):
>    ...   print cnt[0], msg

Well, I do know about this trick, but I don't like using it except
in limited circumstances.  The problem is that people might see
that as part of the external API and think it indicates an optional
parameter.  In your case, you show that it can be used to change
the counter value, but then it's strange to take list instead of
a simple number.

Sometimes I will use it for an extra tiny bit of performance, since
it's a fast lookup.

A couple of times I've done

def _counter(msg, cnt = [0]):
  ...
def counter(msg, cnt = None):
  if cnt is None:
    return _counter(msg)
  return _counter(msg, [cnt])

but for this case it isn't any better than having another module
variable.

What I didn't think about was Gerhard's "counter.cnt" mechanism.
(My mind's still stuck in the 1.4 days :)  I really like that, and
think I'll use it more often in the future.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list