Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #32228

Re: Recommended way to unpack keyword arguments using **kwargs ?

References <CANNB2xteri_DDGGVt-OvkU0mj1LhNBMz5wnctEqJmhorwQqeOQ@mail.gmail.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2012-10-26 11:13 -0600
Subject Re: Recommended way to unpack keyword arguments using **kwargs ?
Newsgroups comp.lang.python
Message-ID <mailman.2900.1351271618.27098.python-list@python.org> (permalink)

Show all headers | View raw


On Fri, Oct 26, 2012 at 10:58 AM, Jeff Jeffries
<jeff.jeffries.iii@gmail.com> wrote:
> I have been doing the following to keep my class declarations short:
>
> class MyClass(MyOtherClass):
>     def __init__(self,*args,**kwargs):
>         self.MyAttr = kwargs.get('Attribute',None) #To get a default
>         MyOtherClass.__init__(self,*args,**kwargs)
>
> Is there a recommended way to get keyword arguments (or default) when using
> ** notation?

It's better form to use .pop() instead of .get(), as if MyClass is
receiving the argument then MyOtherClass is probably not expecting it.

If using Python 3, you can use the keyword-only argument syntax:

def __init__(self, *args, attribute=None, **kwargs):
    # Do something with attribute
    MyOtherClass.__init__(self, *args, **kwargs)


Either way, you should really only do this when there are a large
number of possible arguments or you don't really know what arguments
to expect.  When practical to do so, it is preferable to explicitly
list the arguments so that the method signature can be inspected, e.g.
by the help() command.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Recommended way to unpack keyword arguments using **kwargs ? Ian Kelly <ian.g.kelly@gmail.com> - 2012-10-26 11:13 -0600

csiph-web