Creating a local variable with a parameterized name

Gerrit Holl gerrit.holl at pobox.com
Sun Jan 30 04:14:44 EST 2000


Justin Sheehy wrote on 949166350:
> 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.
> 

...

> my_directory = {}
> my_directory[varname] = 123
> print my_directory[varname]

...

> Directories are handy, and particularly well suited to this sort of
> thing.  Why be any messier than you need to be?

<nitpick>
 Those things are called "dictionairies", not "directories". You could
 use them for a directory structure, however :-)
</nitpick>

-- 
Please correct any bad English you encounter in my email message!
-----BEGIN GEEK CODE BLOCK----- http://www.geekcode.com
Version: 3.12
GCS dpu s-:-- a14 C++++>$ UL++ P--- L+++ E--- W++ N o? K? w--- !O !M !V PS+ PE?
Y? PGP-- t- 5? X? R- tv- b+(++) DI D+ G++ !e !r !y
-----END GEEK CODE BLOCK-----




More information about the Python-list mailing list