automatically naming a global variable
Jeff Epler
jepler at inetnebr.com
Fri May 25 08:12:58 EDT 2001
On 22 May 2001 19:00:50 GMT, Remco Gerlich
<scarblac at pino.selwerd.nl> wrote:
> Chad Everett <chat at linuxsupreme.homeip.net> wrote in comp.lang.python:
>> If I have a string variable defined, how can I create a global
>> variable with the same name as the string?
>>
>> For example:
>>
>> >>> x = "variable_name'
>>
>> Now I want to be able to use x to create a global variable whose
>> name is 'variable_name'
>
> Can someone explain to me why this question comes up so often?
>
> (The answer is something like - this is a bad idea, use a dictionary).
>
> What use is a global variable that you don't know the name of, so you have
> to use <insert favorite hack here> once more to get to its value?
In some other languages, this is "how it's done". For instance,
in TCL, there are "array" variables, which are names of the form
array(key), and correspond roughly to Python dictionaries.
To say "the value of <name>", you write "$name", where name is defined
in the current scope.
In tcl, arrays can only be passed by name .. For instance, one might
write
proc setitem { arrayname keyname value } {
upvar $arrayname array
set array(keyname) value
}
proc getitem { arrayname keyname } {
upvar $arrayname array
return $array(keyname)
}
setitem myarray 1 "hi there"
puts $myarray(1) ;#prints "hi there"
--- the "upvar" statement says "let me refer to the thing with the name
of the first argument in the caller's scope when I use the name given in
the second argument.
Talk about gross! But, anyhow, I suspect it's for desire of something
like "upvar" that people keep asking this question, although a similar
idea probably exists in other languages.
Jeff
More information about the Python-list
mailing list