Answers DSM and Tadeck answer your question directly.
In my scripts, I often use the convenient dict.pop() to handle optional and optional arguments. Here is 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 not contained in kwargs , then by default '' (empty string) is stored in the local prefix variable. If it is specified, then its value is used.
This is usually a compact and readable recipe for writing wrappers for any function: always just passed arguments that you don’t understand, and don’t even know if they exist. If you always go through *args and **kwargs , you make your code slower and require a bit more typing, but if the interface of the called function (in this case print ) changes, you do not need to change your code. This approach reduces development time by supporting all interface changes.
cfi Sep 13 '12 at 9:35 2012-09-13 09:35
source share