[Python-Dev] LOAD_NAME & classes
Guido van Rossum
Wed, 24 Apr 2002 00:49:07 -0400
> It's hard to know what could really help more. If Greg Wilson is
> still running newcomer experiments, I'd like to see what newcomers
> have to say about this:
> x = 2
> def f():
> print x # A
> x = 3
> print x # B
> A: What do you think should happen when the print at A executes?
> B: " " " " " " " " " " B " ?
> What I suspect, but don't know, is that a majority of newcomers who
> expect A to print 2 *also* expect B to print 3. That is, that
> they're thinking x is a global variable, and have no conception of
> local variables in mind.
That's not a fair experiment until after you've given them a good
concept of local and global variables without name conflicts. On the
one hand, the importance of having local variables at all isn't clear
if there are no name conflicts (until you introduce recursion, which I
would *definitely* introduce much later, despite Matthias Felleisen's
teachings :-). But on the other hand, it's easy to show that after
>>> def f():
... greeting = "hello world"
... print greeting
>>> print greeting
there's no global variable 'greeting', which can then be used to
explain that variable assignments create local variables. You don't
need to explain the *reason* for this feature at this point; that'll
be clear by the time you've explained the rest. Next you can explain
the global statement. This appears irrelevant to the proposed
experiment, but it's useful to take away fears that you can't change
globals at all: people coming from other languages will know that that
is important, and worry how Python deals with this. After that you
can show how name conflicts are handled in the "normal" case, where
you shadow a global in a function by assigning to it and then using
it, without a global statement. At some point you should also point
out that if you don't *change* a global, you can use in a function it
without the global statement. This comes so natural that it's easy to
gloss over, especially when the "global" in question is a function or
an imported module; but it *is* an important feature.
*THEN* you are ready for the experiment Tim proposes above.
--Guido van Rossum (home page: http://www.python.org/~guido/)