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

Michael Janssen Janssen@rz.uni-frankfurt.de
Fri Apr 11 20:46:02 2003

On Fri, 11 Apr 2003, Scott Chapman wrote:

> I wasn't trying to show the list anything relating to Perl vs. Python.  I was
> demonstrating how Perl does references and how Python does them.  The Perl
> advocate on the Perl Tutorial list was the fellow I was quoting on the
> original post.  He said that you must use vars() in python to do the trick
> like you do in Perl with it's reference syntax.  He said that this is a
> drawback to Python when you get into deeply nested structures.
> I wanted some opinions from the Python list as to whether or not this is a
> drawback or not from a Python programmers perspective and if there are any
> easier solutions than using vars() or eval() that might work better for
> deeply nested structures, or is there a better way to do the data structures
> altogether.

eval() and ${ } is both as simple, isn't it?

##What happens actually?

d1 = {"a": "one"} set up a string value "one" for a string key "a".

*given* that "one" is a variable (in global namespace) you can do:

---> eval() evaluates the python expression "one" in global namespace.

---> this looks up "one" in a dictionary returned by vars() (try
"print vars()" to get an impression what vars() does).

But although you *can* do it, this is not the python way of handling data.
In other words: you seldom find a python scripts that relies on this kind
of hack. Honest: The best way to reduce problems with eval()/vars() is to
reduce its usage no matter how deep you data structure is.

##Deep data structure with strings to call related variables with eval()

[Disclaimer: this is a complete test scenario. This is *not* the way you
should wite python scripts]

# data at the bottom.
one = 1
two = 2

# a collection
aDict = {1: "one", 2:"two"}

# next level of nesting (upper)
caller = "aDict"

# next level of nesting (deeper)
DeepDict = {"wert": "asdf"}
three = "DeepDict"
aDict[3] = "three"

----> is this what you have meant (If not you should provide your own
example, because it's very likly that no python programmer can provide
one from her/his background)?

eval(eval(caller)[1]) --> 1

eval(eval(caller)[3]) --> "three"
eval(eval(eval(caller)[3]))["wert"] --> "asdf"

Beside the need to count the amount of evals, I can't see a problem with

Note: hopefully nobody actually does this.


It's not clear to me, what's the subject of the example:
A) the way of retrieving data from deep-nested structures?
B) the effect that "one" is modified and the updated value is found via
   ${ %dict{a} }?

A): python does it another way. Shall we give you some examples?
B): why modify a value and retrieve it from somewhere else? When you want
to organize "shared data" you propably better organize it with classes.