Creating a local variable with a parameterized name

Michael Ross mross at rochester.rr.com
Sat Jan 29 21:49:29 EST 2000


Nic Williams wrote:

> 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.

Nic, my initial thought was the same as yours, until I ran across this in
Section 4.1 of the Python Ref Manual, referring to locals() :

" ... The built-in functions globals() and locals() returns a dictionary
representing the current global and local namespace, respectively. The
effect of modifications to this dictionary on the namespace are
undefined."

I found that changing the dictionary returned by locals() works in an
interactive shell, but not when the code is in a module.

This is what made me dig into the Python source... It seems that
internally Python holds the variables for the local frame in a different
data structure than a dictionary.  locals() simply converts this to a
dictionary for convenience.

Justin, thanks for your answer... but I'm trying to pre-condition an
environment that will be used by non-programmers, so I was trying to avoid
the dictionary syntax.

- Mike




More information about the Python-list mailing list