Var substitution

Gerhard Häring gerhard.haering at gmx.de
Thu Jun 27 11:37:26 EDT 2002


Guy wrote in comp.lang.python:
> Hi
> 
> What i'm wanting to know, is there any way of looking at a variables
> value rather than its name.
> 
> Example
> 
> Unix : ${MyVar}
> Dos  : %MyVar%

Python: MyVar

> Both of the above will be subtituted with the values.

In Python, values are bound to names. By using a name on the left-hand
side of =, you bind a value to it. In all other cases, you access the
value with its name.

x = "foo"
Bind the value "foo" to the name x in the current scope (namespace).

print x
Access the value the name "x" in the current namespace refers to.

y.x = "foo"
Bind the value x in the namespace y (which might be a class, class
instance, module, function, ...) to the value "foo".

print y.x
Access the value of the name "x" in the namespace y.

> Example python script (below causes error):
> 
>>>> guy="name"

You bind the value "name" of type string to the name 'guy' in the
current namespace. In this case, the global namespace.

>>>> import os

You import the module os, which does have a namespace of its own.

>>>> os.guy

You try to access 'guy' in the namespace of the os module, which
doesn't exist there.

> This is what should happen :
> 
>>>> import os
>>>> os.name

Sure, the os module has "name" in its namespace, but not "guy". That's
why this works.

> 'nt'

Just for demonstration, as there's no point in it, but you _could_ do
the following:

    import os
    os.guy = "foo"
    print os.guy

Gerhard
-- 
mail:   gerhard <at> bigfoot <dot> de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id AD24C930
public key fingerprint: 3FCC 8700 3012 0A9E B0C9  3667 814B 9CAA AD24 C930
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))



More information about the Python-list mailing list