Dynamic Keyword Arguments in Python?

前端 未结 4 1818
灰色年华
灰色年华 2020-12-01 10:24

Does python have the ability to create dynamic keywords?

For example:

qset.filter(min_price__usd__range=(min_price, max_price))

I w

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 10:42

    You can easily do this by declaring your function like this:

    def filter(**kwargs):
    

    your function will now be passed a dictionary called kwargs that contains the keywords and values passed to your function. Note that, syntactically, the word kwargs is meaningless; the ** is what causes the dynamic keyword behavior.

    You can also do the reverse. If you are calling a function, and you have a dictionary that corresponds to the arguments, you can do

    someFunction(**theDictionary)
    

    There is also the lesser used *foo variant, which causes you to receive an array of arguments. This is similar to normal C vararg arrays.

提交回复
热议问题