[Edu-sig] Using IDLE with students

kirby urner kirby.urner at gmail.com
Fri Aug 17 04:18:34 CEST 2007


On 8/16/07, Richard Guenther <heistooheavy at yahoo.com> wrote:
>

> So I've worked several Python books and tutorials, written both functional
> programs and some OOP, and yet I find myself not real clear on what exactly
> IDLE is ... :-(
>
> Ah well, at least my ubuntu menu launches IDLE in "normal" mode now. :-)
>
> Richard

IDLE is this REPL (read, evaluate, print loop) in the namespace __main__.

If you run a program as an argument to python i.e. as top-level, that's
__main__ too (but without any REPL -- unless you code that in).

So it makes sense that if you're in one of IDLE's text windows, say
looking at test.py and go F5 and/or choose Run, that __main__ now
gets the benefit of whatever gets executed.  That's because you've
just elected to run test.py top-level.

However, if you just *import* test.py, even though test.py will be evaluated,
top-to-bottom, it will *not* populate __main__ because it was not run top
level, only imported.

Example:

test.py has the single line of code:

a = 1

If you are in that test.py code window and Run it top level, you will
(a) prompt a restart of IDLE (if not using -n) and
(b) inherit the contents of __main__ when it's done running:

>>> ===== RESTART =====
>>>
>>> a
1

On the other hand, if you new restart the shell (purging all but the
default namespace), and simply *import*, then the variable 'a' will
not be accessible *except* through the namespace of 'test':

>>> ===== RESTART =====
>>> import test
>>> a

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    a
NameError: name 'a' is not defined
>>> test.a
1
>>> ==========

This behavior holds even if you have no subprocess, but then, instead
of IDLE rebooting __main__ from the menu (or automatically when
choosing Run), you need to exit IDLE and come back in, in order to
clear __main__'s namespace.

Kirby


More information about the Edu-sig mailing list