[Tutor] Perl vs. Python's way of handling references.

Timothy M. Brauch tbrauch@mindless.com
Fri Apr 11 16:13:02 2003


> > The above in python ... You have to say:
> >
> > $ python
> > Python 2.2.1 (#1, Aug 30 2002, 12:15:30)
> > [GCC 3.2 20020822 (Red Hat Linux Rawhide 3.2-4)] on linux2
> > Type "help", "copyright", "credits" or "license" for more
information.
> >
> > >>> one = 1
> > >>> two = 2
> > >>> dict = {'a':'one','b':'two'}
> > >>> print vars()[ dict['a'] ]
> >
> > 1
> >
If I'm not mistaken, and I might be, this is not quite right.  Or, at
least, not how I would do it.

Let's look at this...
>>> one = 1
>>> two = 2
>>> one
1
>>> two
2
>>> my_dict = {'a':'one','b':'two'}
>>> my_dict['a']
'one'

Hmm, but you want the value 'one' is holding.  Try this...

>>> eval(my_dict['a'])
1

Although, I must admit, I am a little confused on the
>>> one = 1
and why it's not
>>> 'one' = 1

Or, why then in the dictionary, you decide 'a':'one', with quotes.  I
think someone is getting sloppy with quotes.  So, let's test this
little fix and watch what we do with quotes.

>>> my_dict['a'] = one
>>> my_dict['a']
1

Ah, so now, you can do this in Python to get the desired effect...
>>> one = 1
>>> two = 2
>>> my_dict = {'a':one,'b':two}
>>> my_dict['a']
1

No need for vals() anything.  This seems intuitive to me.  I mean, if
I look up a word in a real dictionary, I want the definition, not
something that tells me where I can go look to find the definition
(like a memory reference seems to be to me).

Oh, and a point of style.  dict = {...} is bad in Python.  One must be
very careful renaming the default functions like this.

I don't know if I quite answered the question, but maybe at least this
is food for thought.

 - Tim