On 3 May 2007 23:36:11 -0700, Michael <[EMAIL PROTECTED]> wrote:
> On May 2, 6:08 am, Carsten Haese <[EMAIL PROTECTED]> wrote:
> > On Tue, 2007-05-01 at 22:21 -0700, Michael wrote:
> > > Is there a reason for using the closure here?  Using function defaults
> > > seems to give better performance:[...]
> >
> > It does? Not as far as I can measure it to any significant degree on my
> > computer.
>
> I agree the performance gains are minimal.  Using function defaults
> rather than closures, however, seemed much cleaner an more explicit to
> me.  For example, I have been bitten by the following before:
>
> >>> def f(x):
> ...     def g():
> ...         x = x + 1
> ...         return x
> ...     return g
> >>> g = f(3)
> >>> g()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 3, in g
> UnboundLocalError: local variable 'x' referenced before assignment
>
> If you use default arguments, this works as expected:
> >>> def f(x):
> ...     def g(x=x):
> ...         x = x + 1
> ...         return x
> ...     return g
> >>> g = f(3)
> >>> g()
> 4
>

You aren't getting "bit" by any problem with closures - this is a
syntax problem.
Assigning to x within the scope of g() makes x a local variable. x =
x+1 doesn't work, then, because "x+1" can't be evaluated.

If you just used "return x+1" or if you named the local variable in g
something other than "x", the closure approach would also work as
expected.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to