[Python-ideas] For-loop variable scope: simultaneous possession and ingestion of cake
Ron Adam
rrr at ronadam.com
Mon Oct 6 19:03:12 CEST 2008
Carl Johnson wrote:
> Why does the evil default args hack work? Because it immediately
> evaluates the argument and stores the result into the lambda object's
> default values list. So, what we need is a keyword that means
> "immediately evaluate the argument and store the result, instead of
> looking up the name again later." Since I can't think of a good name for
> this, I will use a terrible name for it, "immanentize."
Yep, that is terrible! ;-)
I'm really starting to see this as a non-problem after reading all these
posts. This particular problem is solved much nicer with a class than a
function.
I have two reasons for this, one is classes are the natural structure to
use if you want to save a state. And the other is I would actually prefer
that functions never save states, or even closures. (but that would break
a lot of decorators.)
Here is an example that works as expected with no magic or hidden behaviors.
class Caller(object):
def __init__(self, f, *args, **kwds):
self.f = f
self.args = args
self.kwds = kwds
def __call__(self):
return self.f(*self.args, **self.kwds)
def id(i):return i
L = []
for n in range(10):
L.append(Caller(id, n))
for f in L:
f()
You could go one step further and make the class more specific to the
situation it is being used by defining the __call__ method to do what you
want instead of using a stored function reference.
Something I think would be more beneficial to solve is to be able to pack
and unpack entire function arguments into one signature object easily and
automatically.
def foo(***aks):
...
Ron
More information about the Python-ideas
mailing list