What are python closures realy like?
Tim Chase
python.list at tim.thechases.com
Wed Dec 6 06:44:02 EST 2006
> def foobar(arg1, arg2, arg3):
> def helper(arg):
> do something with arg1 and argument
> def foo():
> do something with arg1 and arg3 and
> call helper
> def bar():
> do something with arg1 and arg2
> def zoo():
> do something with arg2 and arg3 and
> call helper
> # oops; how do I return all these?
> class bag(object):
> pass
> bag = bag()
> bag.foo = foo
> bag.bar = bar
> bag.zoo = zoo
> return bag
>
> which, I think, deserves no further comment...
Could you please explain your reasoning behind why you opted to
create the bag, fill it, and then return it? Usually I see
something like
return foo,bar,zoo
and it would be helpful to understand the reasoning behind why
one would choose one over the other. Some of the off-the-cuff
thoughts in my trying to understand it:
-defining a bag, instantiating a bag and filling it takes a few
extra cycles for each call of foobar() so the returned tuple
should be a hair faster (though perhaps defining a bag class
outside the foobar() function might trim some of this?)
-returning a tuple requires that any additional methods you might
opt to add/return in the future involve adjusting all your code,
whereas the bag method allows you to toss extra methods in the
bag without adjusting every statement that calls foobar()
Are either of these correct? Are there additional reasons I'm
missing?
Thanks,
-tkc
More information about the Python-list
mailing list