Unexpected Python Behavior

Fernando Perez fperez528 at yahoo.com
Mon Oct 4 19:19:53 EDT 2004


Ville Vainio wrote:

>     Andrea> But tell me that
> 
>     Andrea> def foo(x,my_personal_cache_so_please_dont_pass_this_parm=[]):
>     Andrea> ...
> 
>     Andrea> is beautiful and I can sign a paper where is stated that
>     Andrea> you're either kidding or a dork.
> 
> It's not beautiful, but it works, and is already in the language. Come
> on, you are an old C++ hand, you are used to dealing with the horrors
> of chtulhuan proportions daily. I'm a C++ programmer as well, and
> nothing in Python compares to the dirt I deal with every day. Private
> cache in param list is a minor issue.

Sorry to pitch in late, and forgive me if this has already been discussed and
thrown out for some other reason, I didn't follow the whole thread.  Why not
use function attributes for the cache?

In [3]: def foo(x):
   ...:     if x in foo.cache:
   ...:         print 'x=',x,'in cache!'
   ...:     else:
   ...:         print 'new calculation for x:',x
   ...:         foo.cache[x] = 1
   ...:

In [4]: foo.cache={}

In [5]: foo(1)
new calculation for x: 1

In [6]: foo(1)
x= 1 in cache!

In [7]: foo(2)
new calculation for x: 2

In [8]: foo(2)
x= 2 in cache!

I tend to prefer this to the cache-in-args-list approach, but maybe there was a
good reason in the thread (which I didn't read).  You can do this with a
full-blown class which implements __call__, which I do when the function state
is really complex.  But for simple cases where I just need a few things to
enhance a function's behavior, I simply slap the attributes I need on top of
it and I'm on my way.  Simple, clean and pythonic, IMHO.

Cheers,

f



More information about the Python-list mailing list