A scoping question 
Author Message
 A scoping question

In Python, scopes don't nest. The commonly used idiom for this stuff
is

qualified = map( lambda x, localarg = arg: os.path.join(localarg,x),
rawlist)

You declare an optional argument with the expression "arg" as the
default. That expression is resolved in the context where the lambda
is defined.




Sun, 23 Apr 2000 03:00:00 GMT  
 A scoping question

I just stumbled across this (with several changes to remove
unimportant details):

def someFunct(arg):
    print "the arg is ", arg

    rawlist = os.listdir(arg)
    qualified = map( lambda x: os.path.join(arg,x), rawlist)

The problem is in the lambda function, and it's a NameError: arg.
I was wondering what the general rule is on scoping and lambdas.

I'm sure that it's just a fundamental newbie problem, but in
case it helps, I'm using PythonWin 1.4.

Tim

p.s: What a cool little language!



Sun, 23 Apr 2000 03:00:00 GMT  
 A scoping question

Quote:

> I just stumbled across this (with several changes to remove
> unimportant details):

> def someFunct(arg):
>     print "the arg is ", arg

>     rawlist = os.listdir(arg)
>     qualified = map( lambda x: os.path.join(arg,x), rawlist)

> The problem is in the lambda function, and it's a NameError: arg.
> I was wondering what the general rule is on scoping and lambdas.

  The problem is that arg is not in scope inside the lambda. To
fix it, add the default argument "arg=arg" inside your lambda like this:

def someFunct(arg):
  print "the arg is ", arg
  rawlist = os.listdir(arg)
  qualified = map( lambda x,arg=arg: os.path.join(arg,x), rawlist)

  ps- lambdas are really slow if you pass python functions as the
argument. try a for-list instead.

Quote:

> I'm sure that it's just a fundamental newbie problem, but in
> case it helps, I'm using PythonWin 1.4.

> Tim

                                                welcome- dave m.
Quote:

> p.s: What a cool little language!



Sun, 23 Apr 2000 03:00:00 GMT  
 A scoping question

Quote:
> The problem is in the lambda function, and it's a NameError: arg.
> I was wondering what the general rule is on scoping and lambdas.

Check FAQ question 6.10 at http://www.python.org/doc/FAQ.html

Hope that helps!

 Paul Prescod



Mon, 24 Apr 2000 03:00:00 GMT  
 
 [ 4 post ] 

 Relevant Pages 

1. scoping question

2. Annoying Scoping Questions

3. newbie - Scoping question

4. Is this possible: scoping question with exec

5. Tricky scoping question for poor man's debugger

6. python dynamic scoping question

7. Another variable scoping question

8. __module__ / scoping question

9. dynamic scoping question

10. Scoping Question???--Urgent

11. Lexical scoping good, dynamic scoping bad

12. Questions about scoping

 

 
Powered by phpBB® Forum Software