Understanding closures
Alex Martelli
aleax at mac.com
Sun Aug 19 01:38:56 EDT 2007
Ramashish Baranwal <ramashish.lists at gmail.com> wrote:
> Hi,
>
> I want to use variables passed to a function in an inner defined
> function. Something like-
>
> def fun1(method=None):
> def fun2():
> if not method: method = 'GET'
> print '%s: this is fun2' % method
> return
> fun2()
>
> fun1()
>
> However I get this error-
> UnboundLocalError: local variable 'method' referenced before
> assignment
>
> This however works fine.
>
> def fun1(method=None):
> if not method: method = 'GET'
> def fun2():
> print '%s: this is fun2' % method
> return
> fun2()
>
> fun1()
>
> Is there a simple way I can pass on the variables passed to the outer
> function to the inner one without having to use or refer them in the
> outer function?
Sure, just don't ASSIGN TO those names in the inner function. Any name
ASSIGNED TO in a given function is local to that specific function (save
for global statements, which bypass variable of containing functions
anyway).
Alex
More information about the Python-list
mailing list