Migrating from PHP to Python...

Hans Nowak hnowak at cuci.nl
Mon Sep 3 01:30:26 EDT 2001


On 2 Sep 01, at 21:21, Rick Shin wrote:

> >
> > All variables in python are dynamic type. Is that what you were asking?
> >
> > >>> a=1
> > >>> a
> > 1
> > >>> a = 'hello'
> > >>> a
> > 'hello'
> 
> Actually, I was referring to PHP's ability to assign names dynamically to
> variables. For example:
> 
> $var = 'hello';
> $$var = 'world!';
> echo $var . ' ' . $$var;    // prints 'hello world!'
> echo $var . ' ' . $hello;    // prints 'hello world!' too

With some trickery, this is (more or less) possible in Python too, but it's not 
recommended...

>>> var = "hello"
>>> exec("%s = '%s'" % (var, "world"))
>>> hello
'world'

or with a function...

>>> def makephpvar(name, value):
	exec("%s = %s" % (name, repr(value))) in globals()
	
>>> makephpvar(var, "world")  # equivalent to $$var = 'world';
>>> dir()
['__builtins__', '__doc__', '__name__', 'hello', 'makephpvar', 'var']
>>> hello
'world'

Don't try this at home, though... If you want "variable variables", maybe a 
dictionary better suits your needs, to name something.

--Hans Nowak (zephyrfalcon at hvision.nl)
You call me a masterless man. You are wrong. I am my own master.
May Hugh Hefner catch your Rice Rocket!




More information about the Python-list mailing list