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

Discussion in 'Python' started by Ian Kelly, Oct 26, 2012.

  1. Ian Kelly

    Ian Kelly Guest

    On Fri, Oct 26, 2012 at 10:58 AM, Jeff Jeffries
    <> 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.
     
    Ian Kelly, Oct 26, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Edward Diener
    Replies:
    14
    Views:
    5,032
    Josiah Carlson
    Apr 6, 2004
  2. Replies:
    4
    Views:
    1,344
  3. Replies:
    6
    Views:
    473
    Peter Otten
    May 10, 2007
  4. Peter Motzfeldt
    Replies:
    1
    Views:
    160
  5. John Ladasky
    Replies:
    10
    Views:
    253
    Peter Cacioppi
    Oct 8, 2013
Loading...

Share This Page