[Tutor] creating variables at runtime

Kirby Urner urnerk@qwest.net
Wed, 23 Jan 2002 22:57:11 -0800


>
>It's not that you're doing anything wrong.  I'm just trying
>to make clear the distinction between creating new variables
>at the top level, versus inside a program-provided data
>structure.
>
>Kirby

Actually, I wasn't being all that clear myself.  You *are*
creating new instances at the top level *in a module* (the
container).  That satisfies the initial question.

exec() is creating new variables in the namespace of the
containing module, and you're just using the names list
to keep track of the names.  The while loop is internal
to the module, but not internal to a function, so the
entire module is its scope, which is why the exec()
statement works to populate the module itself.

So I take it back.  You did it.  I apologize.

But what I was trying to do is a little different:  write
in interactive raw_input loop *in the shell* that creates
new top-level variables:

Note shell prompts:

 >>> def shell():
         while 1:
            i = raw_input("Name: ")
            if not i:
                break
            names.append(i)
            exec(i + " = C()")


 >>> class C:
         pass

 >>> names = []
 >>> shell()
Name: A
Name: B
Name: C
Name:

 >>> dir()
['C', '__builtins__', '__doc__', '__name__', 'names', 'shell']

A,B and C are gone -- the ones I created in the loop (the
C here is the original class definition).

Because the exec(i + " = C()") statement creates new variables
*locally* to the shell() function -- then they get tossed.

So that was my challenge:  how do you write a raw_input loop
function *in the shell* that creates new variables at the
top level?

Sorry again for not being clear.

Kirby