[Tutor] interactive naming of pointers

Lie Ryan lie.1296 at gmail.com
Thu Jul 16 23:12:28 CEST 2009

Wayne wrote:
> On Thu, Jul 16, 2009 at 9:38 AM, chris Hynes <cjhynes36 at hotmail.com
> <mailto:cjhynes36 at hotmail.com>> wrote:
>     Yeah, I'm not sure if I'm explaining myself well or maybe I'm just
>     trying to make the code too interactive.
>     in my code I would type something like:
>     x=zeros((3,3))
>     so the pointer called "x" is created by the programmer, but within
>     the code. What if I wanted to prompt my keyboard user to type in a
>     word, like "Chris" and then the program would create:
>     Chris=zeros((3,3))
>     Whatever code could make this happen I could loop through it several
>     times, create various array names, and when the operator was done,
>     they would have several arrays created with names of their choosing.
>     When I'm in ipython mode, I would have to type Chris=zeros((3,3)),
>     then Bob=zeros((3,3)) and then Kent=zero((3,3)), three separate
>     statements (and gosh what if I wanted more than just these three?).
>     I want my user to create names for their pointers instead of it
>     already being in the code.
> That's what a dictionary effectively does.

In fact, in python, global name resolution is merely syntax sugar for
accessing the global names dictionary.

If you want to have an interactive prompting in your own program and the
prompting can assign names and stuffs, you should create your own
namespace instead of corrupting the interpreter's global namespace
(which is a huge security risk and is a latent source of bugs).

something like:

mynames = {}

inputting = True
while inputting:
    name = raw_input('name? ')
    data = make_zero()
    mynames[name] = data
    inputting = not raw_input('continue? (leave blank to continue) ')

browsing = True
while browsing:
    name = raw_input('name? ')
    print mynames[name]
    browsing = not raw_input('continue? (leave blank to continue) ')

or if you don't mind using eval/exec:

# a poor man's python interpreter
global_ns = {}
while True:
    prompt = raw_input('>>>')
    exec prompt in global_ns

More information about the Tutor mailing list