0

I have several layers of function calls, passing around a common dictionary of key word arguments:

def func1(**qwargs):
    func2(**qwargs)
    func3(**qwargs)

I would like to supply some default arguments in some of the subsequent function calls, something like this:

def func1(**qwargs):
    func2(arg = qwargs.get("arg", default), **qwargs)
    func3(**qwargs)

The problem with this approach is that if arg is inside qwargs, a TypeError is raised with "got multiple values for keyword argument".

I don't want to set qwargs["arg"] to default, because then func3 gets this argument without warrant. I could make a copy.copy of the qwargs and set "arg" in the copy, but qwargs could have large data structures in it and I don't want to copy them (maybe copy.copy wouldn't, only copy.deepcopy?).

What's the pythonic thing to do here?

4

2 に答える 2

2

を呼び出す目的で別の dict を構築して使用するfunc2だけで、後で を呼び出すためにオリジナルをそのままにしておきfunc3ます。

def func1(**qwargs):
    d = dict(arg=default)
    d.update(qwqargs)
    func2(**d)
    func3(**qwargs)

これは、 in の設定argqwargsをオーバーライドする場合ですdefault。それ以外の場合 ( indefaultの可能な設定をオーバーライドする場合):argqwargs

def func1(**qwargs):
    d = dict(qwargs, arg=default)
    func2(**d)
    func3(**qwargs)

キーワード引数 todictは、位置引数の値をオーバーライドするためです (存在する場合)。

于 2010-04-30T15:38:48.957 に答える
1

同じキーと値で新しいdictを作成するには、使用できます

 newdict=dict(qwargs)

qwargs に非常に多くのキーが含まれていない場合、それは安価です。

可能であれば、関数を書き直して、引数を複数の引数ではなく実際に辞書として取ることができます。

于 2010-04-30T15:53:07.877 に答える