[Tutor] reinitializing namespace

Michael Janssen mi.janssen at gmail.com
Fri Jan 14 20:21:48 CET 2005


On Fri, 14 Jan 2005 09:30:46 +0100, Dimitri D'Or
<dimitri.dor at fssintl.com> wrote:

> Thank you for your answer. Actually, my question is not specific to
> interactive sessions. I've written a script that loads some modules, create
> variables and show figures. What I would like to find, is a command for
> clearing all the created variables and close all figures before beginning
> the execution of the script. This command will be placed at the beginning of
> the script and automatically reinitialize the namespace. The utility of this
> command is to guarantee that all the variables that are available in the
> namespace after the execution of the script were created by it and are not
> remainders from older commands or scripts.

In Python you do this by mentally tracking when and by which code
variables get created and by careful programm design. Most the time
it's as easy as:

var1 = func1()
var2 = func2()

It's obviously easy to track which variable gets created by which
function ;-) It's harder when func1 for example looks like:

def func1():
      global var3
      var3 = "something"
      return "somthing"

this way func1 has the *sideeffect* of setting var3. Sideeffects are
sometimes really bad and it's a good idea to a) document them and b)
use them seldom.

Furthermore, reusing old variables can happen and results in hard to
debug bugs. Look at this for-loop:

meaning_full_variable = None
for thing in list_of_things:
    if strange_condition():
        meaning_full_variable = check(thing)
    print thing, meaning_full_variable

Of course, you will reuse the meaning_full_variable whenever
strange_condition() is not met. The print statment will print out the
actual "thing" but possibly the "meaning_full_variable" from an
earlier run.

You solve this issue by setting meaning_full_variable in every
iteration of this loop:

for thing in list_of_things:
      meaning_full_variable = None
      if strange_condition():
          meaning_full_variable = check(thing)
      print thing, meaning_full_variable 

which is a slightly saner version of the code ;-)

Since such problems are a little hard to debug, you should learn to
get wary when you see code like the above example (feel the problems
before running into them).


The main tactic to minimize namespace problems is to use functions and
classes which comes all with their own namespaces. Perhaps you should
post code, you find problematic, and we might find strategies to
restructure it, so that namespace problems are claryfied.


regards
Michael


More information about the Tutor mailing list