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

Scott Chapman scott_list@mischko.com
Fri Apr 11 16:32:02 2003


On Friday 11 April 2003 13:12, Timothy M. Brauch wrote:
> > > 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.

The quotes are used here to see if it's like Perl.  It isn't.

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

Not really.  Python's got my_dict['a'] pointing at the actual 1 in memory, not 
the variable one:

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
>>> my_dict = {'a':one,'b':two}
>>> my_dict['a']
1
>>> one = 3
>>>
>>> my_dict['a']
1
>>> id (one)
135313084
>>> id (1)
135313168
>>> id (my_dict['a'])
135313168

vars() is needed (or eval()) to do the trick like Perl.  I'm wondering if 
there's a way to do this that works better in deeply nested structures, which 
was the point made by the person on Perl Tutor.


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

Didn't realize that was a built in.

Scott