How To Check If A Key in **kwargs Exists?

后端 未结 6 2022
孤街浪徒
孤街浪徒 2020-12-13 03:09

Python 3.2.3. There were some ideas listed here, which work on regular var\'s, but it seems **kwargs play by different rules... so why doesn\'t this work and how can I check

6条回答
  •  执笔经年
    2020-12-13 03:49

    DSM's and Tadeck's answers answer your question directly.

    In my scripts I often use the convenient dict.pop() to deal with optional, and additional arguments. Here's an example of a simple print() wrapper:

    def my_print(*args, **kwargs):
        prefix = kwargs.pop('prefix', '')
        print(prefix, *args, **kwargs)
    

    Then:

    >>> my_print('eggs')
     eggs
    >>> my_print('eggs', prefix='spam')
    spam eggs
    

    As you can see, if prefix is not contained in kwargs, then the default '' (empty string) is being stored in the local prefix variable. If it is given, then its value is being used.

    This is generally a compact and readable recipe for writing wrappers for any kind of function: Always just pass-through arguments you don't understand, and don't even know if they exist. If you always pass through *args and **kwargs you make your code slower, and requires a bit more typing, but if interfaces of the called function (in this case print) changes, you don't need to change your code. This approach reduces development time while supporting all interface changes.

提交回复
热议问题