[Tutor] inquire

Michael P. Reilly arcege@shore.net
Thu, 11 Jan 2001 10:50:46 -0500 (EST)


> 
> --=====_97922590441=_
> Content-Type: text/plain; charset="us-ascii"
> 
> Dear Sir/Madam,
> 
> Does python offer the function like the "&" in FoxPro? 
> i.e. in foxpro, some code like following:
> 
>             a="I am a"
>             b="a"
>             print &b
> 
> may print the content of variable a.
> Can one do like this in python?
> 
> Many Thanks,
> Xia XQ
> 

You're thinking of "soft references".  You can do that in Python, but
not in the same way; everything is a reference after all.  Because of
the namespace rules in Python, it is easier to use eval (or exec) to do
what you want.

>>> a = "I am a"
>>> b = "a"
>>> print eval(b)
I am a
>>> exec 'print %s' % a
I am a
>>> def foobar(ref):
...   c = 'I am not a'
...   print eval(ref)
...
>>> foobar('a')
I am a
>>> foobar('c')
I am not a
>>> foobar('d')
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in foobar
  File "<string>", line 0, in ?
NameError: d
>>>

You'll notice that the function will either take the reference from the
local variables or the global variables, and raise an exception if
the reference cannot be found.  Inspecting the programs "frames"
can also be a means, but that can get complicated.

What is usually more effective is putting these kinds of references as
members or methods of class instances within your program.  Usually,
you'll find that soft references can be replaced with much better
constructs.

But if you would like to see a real example of these being used, then
look at the source code for the "cmd" standard module.   The class in
the module builds command line interfaces by building method names from
the input string and checking to see if the command exists (or if help
exists for it).

Good luck,
  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------