Re: [dfwPython] Beginner Python Quesiton

From: Stan S.
Sent on: Sunday, December 27, 2009 12:14 PM
To Jeremy, Jeff, Rusty, and Jason,

Happy holidays to all.

Thank you very much for replying to my question.  I will attempt to summarize the responses here, for my own benefit.

-- Stan

= = = = = = = = = = = = 

1.  Python reads variables and function names using LEGB scoping (first local, then enclosing scopes, then the global/module scope, then built-in).

print(i) - (with no global i declared) looks first for a local i, then an enclosing i, then a global i, then a built-in i

2.  Python 2.x assignments default to local, unless the variable is declared with a global keyword.

i = 17  (with no global i declared) sets local variable i

global i
i = 17 sets the global variable i to 17.  If i is not defined yet, i is created.

This makes it hard to assign to a variable in an enclosing scope.  A work-around hack is to use a list element.
        def myfunc():
                i[0] = 17
                def inc():
                        i[0] = i[0] + 1

3.  Python 3.x assignments default to local, unless the variable is declared with a nonlocal or global keyword


New Syntax

PEP 3104: nonlocal statement. Using nonlocal x you can now assign directly to a variable in an outer (but non-global) scope. nonlocal is a new reserved word.

i = 17  (with no global or nonlocal i declared) sets local variable i

global i
i = 17 sets the global variable i to 17.  If i is not defined yet, i is created.

nonlocal i
i = 17 sets variable i in an outer scope to 17 - if i is not previously defined, an error occurs.

Our Sponsors

People in this
Meetup are also in:

Sign up

Meetup members, Log in

By clicking "Sign up" or "Sign up using Facebook", you confirm that you accept our Terms of Service & Privacy Policy