Most pythonic way of assigning keyword arguments using a variable as keyword?

前端 未结 2 1574
梦如初夏
梦如初夏 2020-12-01 16:29

What is the most pythonic way to get around the following problem? From the interactive shell:

>>> def f(a=False):
...     if a:
..         


        
相关标签:
2条回答
  • 2020-12-01 17:22

    In many circumstances you can just use

    f(kw)
    

    as keyword arguments don't have to be specified as keywords, if you specify all arguments before them.

    Python 3 has a syntax for keyword only arguments, but that's not what they are by default.

    Or, building on @zeekay's answer,

    kw = 'a'
    f(**{kw: True})
    

    if you don't want to store kw as a dict, for example if you're also using it as a key in a dictionary lookup elsewhere.

    0 讨论(0)
  • 2020-12-01 17:29

    Use keyword argument unpacking:

    >>> kw = {'a': True}
    
    >>> f(**kw)
    <<< 'a was True'
    
    0 讨论(0)
提交回复
热议问题