Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: Recommended way to unpack keyword arguments using **kwargs ?

Thread Tools

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

Ian Kelly
Posts: n/a
On Fri, Oct 26, 2012 at 10:58 AM, Jeff Jeffries
<(E-Mail Removed)> 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.
Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Is there a simpler way to modify all arguments in a function beforeusing the arguments? Python 20 11-16-2012 09:30 PM
RE: keyword checker - keyword.kwlist Hamilton, William Python 4 05-13-2007 06:31 AM
keyword checker - keyword.kwlist Python 6 05-10-2007 04:53 PM
Keyword arguments in a block, possible with zero arguments? Peter Motzfeldt Ruby 1 03-13-2007 01:33 PM
Difference between default arguments and keyword arguments Edward Diener Python 14 04-05-2004 11:26 PM