Strange Behavior

Paul Rubin http
Mon Oct 16 11:04:42 EDT 2006


Steven D'Aprano <steve at REMOVE.THIS.cybersource.com.au> writes:
> It isn't a bug in Python. At worst, it is a "gotcha", but it is a
> deliberate design decision, and quite useful. For example, this is good
> for caching complicated calculations:
> 
> def function(x, _cache={}):
>     # _cache is initialised to an empty dictionary at compile time
>     if _cache.has_key(x):
>         return _cache[x]

The above can be done explicitly:

     def function(x):
         if function._cache.has_key(x):
             return function._cache[x]
         ...
     # function gets an initially-empty cache
     function._cache = {}

So the existing behavior, while not a bug (since it's documented), may
well be a wart.



More information about the Python-list mailing list