Creating a local variable with a parameterized name
Felix Thibault
felixt at dicksonstreet.com
Sun Jan 30 05:24:44 EST 2000
At 17:57 1/29/00 -0500, Michael Ross wrote:
>I'm new to this, so I hope I'm not missing something obvious...
>
>I want to create a local variable with a passed in name.
>
>I realize I can do the following:
>
>>>> def f(varname):
> cmd = '%s = 123' % varname
> exec(cmd)
> cmd = 'print %s' % varname
> exec(cmd)
>
>>>> f('mike')
>123
>>>>
>
>But exec needs to invoke the parser, which seems to be an extremely
>costly thing to do.
>
>It seems local variables are stored in a special, inaccesible (from
>python) place in the frame object (I've been looking at
>PyFrame_FastToLocals and PyFrame_LocalsToFast). Do I need to write C
>code to do this? A builtin to do this would be nice...
>
>Thanks in advance!
>Mike Ross
>
>--
>http://www.python.org/mailman/listinfo/python-list
>
>
Would something like one of these work?
>>> class Warehouse:
def __init__(self, name, value):
setattr(self, name, value)
def __call__(self, name):
return getattr(self, name)
>>> w = Warehouse('Mike', 123)
>>> w('Mike')
123
>>> class Empty:
pass
>>> w = Empty()
>>> w.Mike = 123
More information about the Python-list
mailing list