user-supplied locals dict for function execution?

Steve Holden steve at holdenweb.com
Mon Mar 20 15:31:10 EST 2006


bruno at modulix wrote:
> Lonnie Princehouse wrote:
> 
>>>What's your use case exactly ?
>>
>>
>>I'm trying to use a function to implicitly update a dictionary.
> 
> 
> I think this was pretty obvious. What I wonder is *why* you want/think
> you need to do such a thing  -I don't mean there can't be no good reason
> to do so, but this has to be a pretty uncommon use case, and some of the
> gurus here may point you to (possibly other and possibly better)
> solutions if you give a bit more context.
> 
> And BTW, please, lauch your python shell and type 'import this', then
> read carefully.
> 
> 
> 
>>The
>>whole point is to avoid the normal dictionary semantics, 
> 
> 
> Yes, but *why ?*
> 
> 
Well, one way would be:

def f(d, ...):
     ...
     d.update(locals())

Seems to work, though it does create a self-reference in the dictionary 
because the dictionary is passed as an argument.

  >>> def f(d, a, b, c=23.0):
  ...     print "a:", a, "b:", b, "c:", c
  ...     d.update(locals())
  ...
  >>> myd = {'a': "this is a", 'x': "this is x"}
  >>> f(myd, 1, 2, 3)
a: 1 b: 2 c: 3
  >>> myd
{'a': 1, 'c': 3, 'b': 2, 'd': {...}, 'x': 'this is x'}
  >>>
I can't think of a way to wrap this up as a decorator, though.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd                 www.holdenweb.com
Love me, love my blog         holdenweb.blogspot.com




More information about the Python-list mailing list