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

Discussão em 'Python' iniciado por Stack, Março 1, 2025.

  1. Stack

    Stack Membro Participativo

    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!

    Continue reading...

Compartilhe esta Página