[Tutor] interactive naming of pointers

Wayne srilyk at gmail.com
Thu Jul 16 18:22:51 CEST 2009


On Thu, Jul 16, 2009 at 9:38 AM, chris Hynes <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 [1]: grid = {}

In [3]: grid['chris'] = [1, 2, 3]

In [4]: grid['bob'] = [3, 2, 1]

In [5]: def func(grid):
   ...:     value = raw_input("Enter the name: ")
   ...:     grid[value] = [1,1,1]
   ...:
   ...:

In [6]: grid
Out[6]: {'bob': [3, 2, 1], 'chris': [1, 2, 3]}

In [7]: func(grid)
Enter the name: Mr. Mann

In [8]: grid
Out[8]: {'Mr. Mann': [1, 1, 1], 'bob': [3, 2, 1], 'chris': [1, 2, 3]}

In [9]: grid['bob']
Out[9]: [3, 2, 1]

The key values are unique, just like they would be if you declared them as:

chris = [1,2,3]

Of course I suppose if you REALLY wanted to use the provided names as
variables you could do something that is both pointless and insane:

def use_variable():
    vname = raw_input("Enter the name of the variable: ")
    value = raw_input("Enter the value: ")
    f = open('insane.py', 'w')
    f.write(vname+'='+value)
    f.close()

use_variable()
from insane import *

Tested:

In [11]: use_var()
Enter the var name: foo
Enter the value: 'bar'

In [12]: from insane import *

In [13]: foo
Out[13]: 'bar'

But really, never, ever do this even if it's possible. I can't think of one
single reason that it would be a) a good idea, or b) necessary. Of course I
may be wrong and there is a single reason, but your case is not it.

> 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.

It's been stated several times in several ways that dictionaries do this. So
use a dictionary!

-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090716/1b633f1d/attachment.htm>


More information about the Tutor mailing list