Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

"unpacking" a passed dictionary into the function's name space in Python?

In the work I do, I often have parameters that I need to group into subsets for convenience:

d1 = {'x':1,'y':2}
d2 = {'a':3,'b':4}

I do this by passing in multiple dictionaries. Most of the time I use the passed dictionary directly, i.e.:

def f(d1,d2):
    for k in d1:
        blah( d1[k] )

In some functions I need to access the variables directly, and things become cumbersome; I really want those variables in the local name space. I want to be able to do something like:

def f(d1,d2)
    locals().update(d1)
    blah(x)
    blah(y)    

but the updates to the dictionary that locals() returns aren't guaranteed to actually update the namespace.

Here's the obvious manual way:

def f(d1,d2):
    x,y,a,b = d1['x'],d1['y'],d2['a'],d2['b']
    blah(x)
    return {'x':x,'y':y}, {'a':a,'b':b}

This results in three repetitions of the parameter list per function. This can be automated with a decorator:

def unpack_and_repack(f):
    def f_new(d1, d2):
        x,y,a,b = f(d1['x'],d1['y'],d2['a'],d3['b'])
        return {'x':x,'y':y}, {'a':a,'b':b}
    return f_new
@unpack
def f(x,y,a,b):
    blah(x)
    blah(y)
    return x,y,a,b

This results in three repetitions for the decorator, plus two per function, so it's better if you have a lot of functions.

Is there a better way? Maybe something using eval? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can always pass a dictionary as an argument to a function. For instance,

dict = {'a':1, 'b':2}
def myFunc(a=0, b=0, c=0):
    print(a,b,c)
myFunc(**dict)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...