Creating a local variable with a parameterized name

Justin Sheehy dworkin at ccs.neu.edu
Sat Jan 29 18:19:10 EST 2000


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
> >>>
> 
> But exec needs to invoke the parser, which seems to be an extremely
> costly thing to do.

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?

That is, instead of things like:

cmd = '%s = 123' % varname 
exec(cmd) 
cmd = 'print %s' % varname 
exec(cmd) 

You could probably do things like this:

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?

-Justin

 




More information about the Python-list mailing list