[Courses] [python] Lesson 3: variable scope

Monique Y. Mudama monique at bounceswoosh.org
Thu Jul 7 18:28:03 UTC 2011


On Wed, Jul  6 at 19:16, Akkana Peck penned:
> Brad and Monique wanted to know about variable scoping. This is
> a relatively advanced topic that will probably only make sense to
> folks who have done a fair amount of programming in other languages.
> So, beginners, feel free to skip this message -- you won't need it
> for anything in this class.

[snip]

> As I said, it's confusing, and I've never found a good write-up on
> it -- a lot of Python books seem to gloss over scoping entirely, and
> most of what I just wrote, I determined empirically by trying it,
> IMHO, it's one of the language's weakest points. Happily, you can
> mostly avoid it by using objects and functions instead of globals.

I found some relevant links, but none of them are as straightforward
as I'd like.  Brad, maybe these will help?

Warning: language geekery follows!

http://docs.python.org/tutorial/classes.html#python-scopes-and-namespaces

The above link specifically talks about scope for namespaces, but I
suspect it all applies to scoping in general. 

(
My gut/guess is that python would, strictly speaking, say it's not so
much that your variable "doesn't have a namespace" but rather that it is
"using the default namespace" .... ahah! suspicion confirmed:

https://secure.wikimedia.org/wikibooks/en/wiki/Python_Programming/Basic_syntax#Scope

"When you first start the Python interpreter (i.e., in interactive
mode), you can list the objects in the current (or default) namespace
using this function"
)

... But I'll admit that the first link kind of made my eyes cross, and
I probably won't put a serious effort into understanding it
until/unless I need to.  But the first link has a very interesting,
somewhat surprising sentence: "A special quirk of Python is that . if
no global statement is in effect . assignments to names always go into
the innermost scope"

This link goes into more detail about that "special quirk", explaining
how to modify global variables:

http://www.rexx.com/~dkuhlman/python_101/python_101.html#SECTION004340000000000000000

-- 
monique


More information about the Courses mailing list