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!
The ** operator is used to pack and unpack dictionary in Python and is useful for sending them to a function.
While a single asterisk is used to unpack lists and tuples, the double-asterisk (**) is used to unpack dictionaries.
Introduction. Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement. As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, * .
Both * and ** are the operators that perform packing and unpacking in Python. The * operator (quite often associated with args) can be used with any iterable (such as a tuple, list and strings), whereas the ** operator, (quite often associated with kwargs) can only be used on dictionaries.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With