names of parameters as string
Peter Otten
__peter__ at web.de
Sat Oct 30 07:18:02 EDT 2004
Terry Reedy wrote:
>
> "andrea valle" <andrea.valle at unito.it> wrote in message
> news:1CC54D90-2A40-11D9-A5B8-0003939C968C at unito.it...
>>Suppose I have a string and I'd like to create a variable with its name.
>>How can I do that?
>
> globals['varname'] = 3
>
> difficult or impossible for function locals
Not difficult - only ugly, slow, and dangerous:
>>> def f(name, value):
... a, b, c = 1, 2, 3
... # FIXME put code to check name is really a name here
... exec "%s=value" % name
... loc = locals()
... del loc["name"]
... del loc["value"]
... return "%s = %d" % ("+".join(loc.keys()), sum(loc.values()))
...
>>> f("x", 10)
'a+c+b+x = 16'
>>> f("x,y", (10,20))
'a+c+b+y+x = 36'
Peter
More information about the Python-list
mailing list