[Tutor] creating variables at runtime

Kirby Urner urnerk@qwest.net
Wed, 23 Jan 2002 21:16:00 -0800


At 09:58 PM 1/23/2002 -0700, Paul Sidorsky wrote:

>This is indeed doable:
>
> >>> class MyClass: pass
>
> >>> userinput = "NARF"
> >>> exec(userinput + " = MyClass()")
> >>> NARF
><__main__.MyClass instance at 00B59A8C>
> >>>

I think if you want to show how to create user-named
objects top-level, you should do so from within an
input loop using raw_input("prompt").

The way you show above, as a shell interaction, doesn't
really address the problem, because you're at top level
in the shell already.  In this context, it makes no
sense to use the exec(), as you can just as well go:

   >>> NARF = MyClass()

and be done with it.

How to create top-level user-named objects from within
a raw_input() loop is actually a little more difficult.
It takes some rather tricky Python.

Kirby