namespace hacking question

alex23 wuwei23 at gmail.com
Thu Sep 30 20:49:37 EDT 2010


kj <no.em... at please.post> wrote:
> This is a recurrent situation: I want to initialize a whole bunch
> of local variables in a uniform way, but after initialization, I
> need to do different things with the various variables.
>
> What I end up doing is using a dict:
>
> d = dict()
> for v in ('spam', 'ham', 'eggs'):
>     d[v] = init(v)
>
> foo(d['spam'])
> bar(d['ham'])
> baz(d['eggs'])
>
> This is fine, but I'd like to get rid of the tedium of typing all
> those extra d['...']s.

Here's an approach that uses a decorator. It requires strings to be
passed, so it's not an exact fit for your requirement, but it's very
straightforward:

d = dict(
  spam = 1,
  ham = 2,
  eggs = 3
)

def argdispatch(func):
  def _wrapper(*args):
    args = [d[k] for k in args if k in d]
    return func(*args)
  return _wrapper

@argdispatch
def foo(x):
  print x

@argdispatch
def bar(x):
  print x*2

>>> foo('spam')
1
>>> bar('spam')
2
>>>

With a good editor, it should even take care of one of the quotes for
you ;)



More information about the Python-list mailing list