question about scope

bruno at modulix onurb at xiludom.gro
Thu Feb 16 17:23:35 EST 2006


John Salerno wrote:
> Here's a sentence from Learning Python:
> 
> "Names not assigned a value in the function definition are assumed to be
> enclosing scope locals (in an enclosing def), globals (in the enclosing
> module's namespace) or built-in (in the predefined __builtin__ names
> module Python provides."
> 
> I have trouble reading this sentence. First, I don't understand if the
> word 'enclosing' is a verb or an adjective.

second one

> The whole flow of the
> sentence seems convoluted.

A bit, yes. In short: if a name is used in a function whithout having
been previously assigned in the body of this function, then this name is
looked up first in the enclosing functions definitions (python's
functions can be nested), then in the global (read : module) namespace,
then in the built-in namespace.

And if it's not found, it raises a NameError !-)

> But my real question is this, which is related to the above:
> 
> "Name references search at most four scopes: local, then enclosing
> functions (if any), then global, then built-in."
> 
> I understand what global and built-in are, and I thought I understood
> the concept of local too, but when I got to this sentence (and the
> previous sentence), I became confused about the first two scopes. What's
> the difference between 'local' and 'enclosing functions'? 

This:

def outer_function():
  a = "a in outer"
  def inner_function():
     print "in inner, a = %s" % a
  inner_function()


Python functions can be nested (bis).

>I thought that
> the only way to create a local namespace was if there *was* a function
> definition,

Yes. But since functions definitions can be nested...

> so now I'm confused by the apparent difference that the
> authors are referring to. What's an example of a local scope without
> having a function definition?

I don't know.

> Loops and if statements, perhaps?

Nope, AFAICT.

> And feel free to dissect that first sentence up above, because I just
> don't get it.

Done.



-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list