[Edu-sig] Function Question -- I'm confused...

Christopher A. Craig com-nospam@ccraig.org
18 Sep 2001 08:21:27 -0400


agauld@crosswinds.net writes:

> Since  version 2 thats true. Its whats called embedded scopes
> Thus you can do this:
> 
> def foo():
>    def bar():
>        print "Hello from bar"
>    bar()
[stuff deleted]
> In earlier versions of Python I think you could still type 
> the code but bar would still be seen at the module level.

This example does not use nested scoping, and will work correctly
Python 1.5

Nested scopes allow an embedded function to see the variables of its
parent.  For example this code:

def foo(input):
  def factorial(a):
    if a==0: return 1
    else: return a*factorial(a-1)
  return factorial(input)

would give an error without nested scoping (which must be explicitly
turned on in 2.1 BTW), because the function 'factorial' is defined in
foo, but not in factorial itself.  This also caused problems with the
use of lambdas because you frequently had to do things like

map(lambda a, var=var: a+var, list)

to get them to work (because var would not be defined in the scope of
the lambda unless it was explicitly passed in).  

-- 
Christopher A. Craig <com-nospam@ccraig.org>
"Have you ever commented: 'If I drive fast enough at the red light,
it'll appear green.'" - The Nerdity Test