Friday, May 20, 2011

Adding other arguments when using *args and **kwargs in python

Sometimes you need to use *args and **kwargs to pass your positional and keyword args to another class. But what if your class takes an additional argument you don't want to pass to the super class? Here are a couple of options.

Add a new positional argument
  def __init__(self, a_list, *args, **kwargs):
    super(MyClass, self).__init__(*args, **kwargs)
    self._mylist = a_list

Add a new keyword argument
  def __init__(self, *args, **kwargs):
    self._mylist = kwargs.pop('a_list', ['some', 'default', 'list'])
    super(MyClass, self).__init__(*args, **kwargs)

No comments: