Creating a local variable with a parameterized name

Nic Williams nic at csee.uq.edu.au
Sat Jan 29 20:43:20 EST 2000


In article <vndk8ksmpox.fsf at betelgeuse.ccs.neu.edu>,
  Justin Sheehy <dworkin at ccs.neu.edu> wrote:
> Michael Ross <mross at rochester.rr.com> writes:
>
> > 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
>
> As you have discovered, there are ways to do that, but none of them
> are pretty.  Are you sure that you really need the name to be a
> variable on its own, and that a dictionary wouldn't do?
[cut example]
> my_directory = {}
> my_directory[varname] = 123
> print my_directory[varname]
>
> Instead of creating a variable whose name is the value of 'varname',
> it makes a directory with a key equal to the value of 'varname'.
> There are very few situations of this type that I can think of where
> this would not be sufficient.
>
> Directories are handy, and particularly well suited to this sort of
> thing.  Why be any messier than you need to be?

Michael if you really need to insert the variable into the local name
space then be aware of the built-in functions global() and locals()
which return dictionaries holding the global and local symbol tables,
respectively. There is also vars([object]) which gives an object's
symbol table or (when no parameter is given) the local symbol table.

The result isn't much more attractive than Justin's but you do insert
the variable into the 'official' local space:

def f(name):
	locals()[name]=123
	print locals()[name]

Nic


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list