modifying locals

Tino Wildenhain tino at wildenhain.de
Fri Oct 31 02:10:05 EDT 2008


Hi John,

John [H2O] wrote:
> 
> 
> Steven D'Aprano-7 wrote:
>> What you are actually trying to do is unclear to me. Perhaps you could 
>> try explaining better with a more concrete example?
>>
>> -- 
>> Steven
>> --
>>
> 
> Actually, maybe a LACK of an example would make it simpler. What I'm after
> is a function, to which I can pass a dictionary defined from locals(), then
> in the function I would modify some of the variables from the dictionary.
> But I want the modifications to be 'seen' by the method that called the
> function without passing them back via return.

Well a method belongs to a class, so the most cleanest way would be
to store the values in the respective instance.

If you want to modify just arbitrary callers objects, just hand them
to your method our function as argument and modify them there (e.g.
dicts can be modified in place for example)

Also, locals() already returns a dict, no need for the exec
trickery. You can just modify it:

 >>> locals()["foo"]="bar"
 >>> foo
'bar'


> Ideally, I would prefer not to use global, as I think (due to other problem
> in my scripting) this might cause problems.

I strongly suspect that you are doing something much too complicated.

the "modify a few of the elements..." is where it gets interesting.
What are you doing? Is it just that you try to emulate a switch
statement to save some typing?

> Currently I these two possibilities:
> 
> def myFunction(D):
>     for key,item in D.iteritems():
>         exec "%s = %s" % (key, item) 
> 
>      modify a few of the elements...
>      return locals()

        locals().update(D) would have done the same :)

...

Regards
Tino
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3241 bytes
Desc: S/MIME Cryptographic Signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20081031/bcc4e8d3/attachment-0001.bin>


More information about the Python-list mailing list