variable visiblity

Gabor Nagy linux42 at freemail.c3.hu
Wed Apr 16 09:35:00 EDT 2003


Hi!

How can I access the "parent" function's local variable from a nested
function?

example:
def foo(par):
	def f(x): print x, par
	f(0)

SyntaxWarning: local name 'par' in 'foo' shadows use of 'par' as global in
nested scope 'f'
when run, prints x, then
...in f NameError: global name 'par' is not defined

Why: I'd like to use filter( f, mysequence) in foo.
f can only have one parameter, the sequence element. I need to pass it
something else to compare to this would be par.

Right now I do things like:
filter( f, map( None, mysequence, [par] * len(mysequence)))
but I feel that this is quite hard to read, and is not a "good" way to do
the thing.

I can use a non-nested f, and it works. I would like to make it nested, if
possible.

So, as you see, I can accept if the solution is something different from
what I had in my mind, I simply want it simple, and quick.

Regards,
Gee





More information about the Python-list mailing list