[Python-Dev] arguments policy: **kwargs.pop()

Greg Ewing greg.ewing at canterbury.ac.nz
Sat Apr 12 02:25:08 CEST 2014


> On 11/04/14 21:50, Chris Barker wrote:
> 
>>On Thu, Apr 10, 2014 at 7:12 PM, Christian Tismer <tismer at stackless.com>wrote:
>>
>>>    def __init__(self, **kwargs):
>>>        first_arg = kwargs.pop('option_1', somedefault)
>>>        ...
>>>        nth_arg = kwargs.pop('option_n', somedefault')
>>>        ...
>>
>> Is:
>>
>>    def __init__(self, option_1=some_default, option_n=some_default,
>>**kwargs):
>>
>>*that* much harder to write?

I've done this kind of thing (extracting arguments out of **kwds)
in various places in PyGUI, but the situation is somewhat special.
Most classes in PyGUI have an api that accepts *any* of the object's
properties as keyword arguments to the constructor, implemented by
code in the base class's __init__ method. It would be impractical
to explicitly document all of them as constructor args, so I don't.
I just say in one place in the docs that this is general behaviour
to be expected of all PyGUI classes.

Sometimes a class needs to treat the initial values of some of its
properties in a special way, instead of just passing them on to the
base __init__. But this is an implementation detail -- having those
particular args appear explicitly in the signature, but not any of
the others, would serve no purpose, and would just clutter up the
function header. In that situation, I find the extract-from-kwds
style is often easier to read.

Also, often I just want to *read* the value of some arguments,
without popping them. Putting all of those in as explicit keyword
args would mean explicitly passing them on to the base __init__,
further cluttering up the code.

-- 
Greg


More information about the Python-Dev mailing list