Is the behavior expected?

Diez B. Roggisch deets at nospam.web.de
Wed Nov 26 10:52:39 EST 2008


Alphones wrote:

> On 11月26日, 下午9时28分, bearophileH... at lycos.com wrote:
>> Alphones:
>>
>> > it is a little deferent from other script language.
>>
>> See also here:http://en.wikipedia.org/wiki/Dynamic_scope#Dynamic_scoping
>>
>> Python doesn't have such automatic closures, probably for performance
>> reasons and/or maybe to keep its C implementation simpler (maybe other
>> people here can give you an explanation of this, I too am curious).
>>
>> Bye,
>> bearophile
> 
> i encountered this problem when i'm writing a program for packaging
> files.
> the program generates tasks according to description file.
> and tasks are deferent from each other, and should be excuted at the
> last of program.
> 
> i have experience on Lua and have learned about scheme and haskell, so
> i wrote the wrong code in python.
> 
> now my solution is, using class taskCreator to create tasks and put
> them into tasklist.
> class taskCreator:
>     def __init__(self, proc, input, output):
>         self.proc = proc
>         self.input = input
>         self.output = output
>     def call(self):
>         return self.proc.call(self.input, self.output)
> 'proc' is generated by procCreators, it's specified.
> 
> it looks more complex than lambda one.
> 
> is there any other simple way to implement it?
> and does the taskCreator mean 'create a new scope'?

Not exactly, but there is a saying:

"Closures are a poor man's objects. And objects are a poor man's closures."

What you did creating a class and instantiating was to capture the
parameters you needed at a time, and using them within call at another
time.

A similar thing happens when you create a lambda with arguments assigned, as
I showed you - as then as part of the closure of the lambda there are the
names in it's parameter list, assigned to the values the right hand sides
had at the time being.

Depending on what you want to do, both approaches - classes or closures -
are valid. The more complex a problem gets, the more explicit & powerful a
class becomes, where it might be a bit of an overhead for really simple
problems.

One thing for example classes allow - which is interesting for you - is that
it is easy to look into them, for debugging/tracing. You can take a
taskCreator (BTW, read PEP 8 about naming conventions in python) and see
what is in there, e.g. logging it before executing the task or some such.

OTOH, a lambda (or function) is an opaque thing you can't ask such things,
making life a bit harder sometimes.

Diez





More information about the Python-list mailing list