Can you combine keyword argument expansion with regular keyword arguments?
-
27-05-2021 - |
質問
What I want to do is this:
logged_in = {
'logged_in': True,
'username' : 'myself',
}
print render_template('/path/to/template.html',
**logged_in,
title = 'My page title',
more = 'even more stuff',
)
But that doesn't work. Is there any way to combine a dictionary expansion with explicit arguments, or would I need to define the explicit arguments in second dictionary, merge the two, and expand the result?
解決
Keyword expansion must be at the end.
print render_template('/path/to/template.html',
title = 'My page title',
more = 'even more stuff',
**logged_in
)
他のヒント
Yes, you just have it backwards. The keyword expansion must be at the end.
def foo(a,b,c,d):
print [a,b,c,d]
kwargs = {'b':2,'c':3}
foo(1,d=4,**kwargs)
# prints [1, 2, 3, 4]
The above work because they are in proper order, which is unnamed arguments, named, then keyword expansion (while the *
expression can go either before or after the named arguments but not after the keyword expansion). If you were to do these, however, it would be a syntax error:
foo(1,**kwargs,d=4)
foo(d=4,**kwargs,1)
foo(d=4,1,**kwargs)
所属していません StackOverflow