using "private" parameters as static storage?
Arnaud Delobelle
arnodel at googlemail.com
Thu Nov 13 17:23:11 EST 2008
Aaron Brady <castironpi at gmail.com> writes:
> One way around it, which I like the idea of but I'll be honest, I've
> never used, is getting a function a 'self' parameter. You could make
> it a dictionary or a blank container object, or just the function
> itself.
>
> @self_param
> def spam( self ):
> self._count[0] += 1 #<--- how to initialize?
> return "spam " * self._count[0]
>
> Only problem is, how do you initialize _count?
>
> Perhaps 'self_param' can take some initializers, and just initialize
> them off of **kwargs in the construction.
>
> @self_param( _count= [] )
> def spam( self ):
> self._count[0] += 1
> return "spam " * self._count[0]
>
> Looks really pretty (imo), but untested.
Rummaging through my ~/python/junk/ I found the almost exact same:
class NS(object):
def __init__(self, dict):
self.__dict__.update(dict)
def static(**vars):
ns = NS(vars)
def deco(f):
return lambda *args, **kwargs: f(ns, *args, **kwargs)
return deco
@static(ncalls=0, history=[])
def foo(ns, x):
ns.ncalls += 1
ns.history.append(x)
print "Number of calls: %s\nHistory:%s" % (ns.ncalls, ns.history)
>>> foo(3)
Number of calls: 1
History:[3]
>>> foo(5)
Number of calls: 2
History:[3, 5]
>>> foo('spam')
Number of calls: 3
History:[3, 5, 'spam']
>>>
--
Arnaud
More information about the Python-list
mailing list