[Zope] Scoping question (Python scripts)

Kirby Urner pdx4d@teleport.com
Mon, 09 Apr 2001 00:38:55 -0700


I'm unclear on how scoping is handled in Python scripts.

=====
## parameters = name
print "Hello %s" % name
return printed
=====

works as a script but:

=====
## parameters = name
print function()
print "Hello %s" % name
return printed

def function():
   return "Goodbye"
=====

does not -- because 'function' is not found.  However:

=====
## parameters = name
def function():
   return "Goodbye"

# Main
print function()
print "Hello %s" % name
return printed

=====

is OK, as 'function' is defined above the main stuff.  However
I can't get 'function' to see another function e.g.:


=====
## parameters = name

def add2(a):
   return a+2

def function():
   n = add2(3)
   return "Goodbye"

# Main
print function()
print "Hello %s" % name
return printed

=====

'add2' won't be found, I guess because it's "two levels deep" (??).
However, it'll work if I make 'add2' internal to 'function'...

=====
## parameters = name

def function():
   def add2(a):
      return a+2

   n = add2(3)
   return "Goodbye"

# Main
print function()
print "Hello %s" % name
return printed

=====

So what are the rules here?  I'm used to Python modules with one 
shared scope for all top-level function defs, no matter what level
they're called from.  Why can't 'add2' be defined at the same 
level as 'function' (above), or is there syntax to make this work
(I've been trying stuff like script.add2(3) or context.add2(3) 
but that doesn't help).

Help?

Kirby