automatically naming a global variable

Rainer Deyke root at rainerdeyke.com
Tue May 22 17:17:30 EDT 2001


"Remco Gerlich" <scarblac at pino.selwerd.nl> wrote in message
news:slrn9gldmn.kdc.scarblac at pino.selwerd.nl...
> Chad Everett <chat at linuxsupreme.homeip.net> wrote in comp.lang.python:
> > If I have a string variable defined, how can I create a global
> > variable with the same name as the string?
> >
> > For example:
> >
> > >>> x = "variable_name'
> >
> > Now I want to be able to use x to create a global variable whose
> > name is 'variable_name'
>
> Can someone explain to me why this question comes up so often?
>
> (The answer is something like - this is a bad idea, use a dictionary).

It might not be such a bad idea in some cases.  Consider a module with
functions like these:

def do_a():
  try:
    something.a()
  except SomeError:
    pass

def do_b():
  try:
    something.b()
  except SomeError:
    pass

Functions 'do_a' and 'do_b' are structurally very similar.  Now suppose that
you have a whole bunch of these functions, and they're quite a bit bigger.
You want to minimize the amount of effort involved in adding new similar
functions.  You also want to minimize the amount of effort involved in
changing all of these functions in a similar way.  You do this by factoring
out the commonality:

def do(name):
  try:
    getattr(something, name)()
  except SomeError:
    pass

def do_a():
  do('a')

def do_b():
  do('b')

However, this code still contains redundancy, which is a potential source of
errors.  The redundancy can be removed by acting directly on the namespace
dictionary:

for name in ('a', 'b'):
  def f(name=name):
    try:
      getattr(something, name)()
    except SomeError:
      pass
  globals()['do_' + name'] = f


This code may be less readable than the original, but it meets the design
goal of minimizing the amount of effort it takes to add a new similar
function.  Note that simply using a new dictionary instead of 'globals()' is
not an option because it changes the interface of the module.  Also note
that there is no more danger of a name collision than in any other module.


--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games           -           http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor





More information about the Python-list mailing list