2

A problem meeted in rewriting a python program.

I move some previous global variables into a dictionay, so I have to rewrite the functions which have used those variables.

For example,

#old one
a, b = 1, 2    
def func(c):
    print a+b+c

#new one
d = dict(a=1,b=2)
def func(c,d):
    a = d['a']
    b = d['b']
    print a+b+c

As the dictionary d is large, so I'm seeking a something like this

d = dict(a=1,b=2)
def func(c,d):
    locals().update(d)
    print a+b+c

I have tried __dict__.update(d), however __dict__ can't be accessed directly.

Or for key,value in d.items(): setattr(obj,key,value) is possible? If yes, how to set the obj to the function itself?

Syrtis Major
  • 3,791
  • 1
  • 30
  • 40
  • 1
    Is there some reason you can't just use `d['a']`, `d['b']`, etc? Or in other words, how is doing this going to help you with anything? – korylprince Aug 28 '13 at 03:24
  • How about using eval? `print eval('a+b+c',globals(),dict(d,c=c))`? – Vaughn Cato Aug 28 '13 at 03:27
  • 4
    See http://stackoverflow.com/questions/1450275/modifying-locals-in-python / Basically you *can* do this on python2, but not python3, but you *shouldn't* do it at all. – korylprince Aug 28 '13 at 03:27
  • @VaughnCato That's not going to modify locals. – korylprince Aug 28 '13 at 03:29
  • 1
    @korylprince: No, but the dictionary becomes the locals, which may be all that is needed. – Vaughn Cato Aug 28 '13 at 03:30
  • @korylprince Because d has many keys, it's a lot of work to change each var to d['var']. Thanks for your usefull discussion, sorry for my ambiguous question :) . `exec` or `eval` seems to be a good solution, maybe I could use Decorator to wrap the function with few modifications. – Syrtis Major Aug 28 '13 at 04:34
  • Maybe your editor has an option to "rename" the local variables to the dict-key pair? – kqr Aug 28 '13 at 05:31
  • @substructure Just iterate through `d.items()`. That yields (key,value) pairs. – korylprince Aug 28 '13 at 13:56
  • @korylprince Thanks. However, I want to use these items separately. – Syrtis Major Aug 29 '13 at 00:38

3 Answers3

1

What you could do instead is to evaluate your expression using the dictionary as the local variables:

def func(c,d):
    print eval('a+b+c',globals(),dict(d,c=c))

func(3,dict(a=1,b=2))
Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
1

You could use in clause of an exec statement. In the in clause you may provide namespace(s) for Python to search when executing a string. Documentation


For example:

>>> d = dict(a=1, b=2)
>>> def func(c,d):
        exec 'print a+b+c' in d, locals()


>>> func(5,d)
8
0

You can't create local variables programmatically in that way.

Instead, just use the dictionary directly by accessing its keys.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384