namespaces & indentation

Steve Holden sholden at holdenweb.com
Fri Dec 22 17:57:25 EST 2000


Chris Schaller <Chris.Schaller at web.de> wrote in message
news:920f54$m2f$1 at news.mch.sbs.de...
> Dear Pythoners...
>
>   I always thought that I understood Python's scoping, but then I came
across
> that code:
> > def t(x):
> >   if x == 1:
> >     c = 'yeah'
> >   return c
>
> If I execute t(1), I'll get 'yeah', but otherwise there'll be an error
> message.  According to the indentation level c is only valid within the
> if-clause, but not on the outside.  So I guess, the indentation level only
> defines the lines of code that belong to the if-clause, but has nothing to
do
> with scopes.

The indentation level has nothgin to do with scopes!  The scope of c is the
function definition, because c is bound (assigned to) within the function
body.  The interpreter therefore expects to find c in the local namespace.

So, when x == 1 you return the value 'yeah' because that's what you assigned
to c.

When x != 1 you get an error, because the interpreter (having told itself
during compilation that c is local to the function) can't find c in the
function's namespace, because you haven't bound a value to it!

>
>   That's very confusing, I've already programmed a lot in Python, but only
> due to a program error (I forgot to initialize c at the beginning of the
> function - a common error) and an unsuccessful test this happened to a
program
> after months of error-free running.
>
>   Any comments?
>
I think you understand the namespace rules quite well, you just hadn't
previously realized that names are created dynamically on assignment rather
than statically during compilation.  If you haven't assigned a value to them
you get an UnboundLocalError exception (which describes the problem quite
succinctly, don't you think?).

> bye
>   Chris...
>
Has this helped?

regards
 Steve







More information about the Python-list mailing list