Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass extra argument when creating object that uses ** (double star) syntax in python?

How do I pass an extra argument "page_name" when creating NotebookPage object below? I get the error below:

class NotebookPage(wx.Panel):

    def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)


NotebookPage(self, name='NotebookPage0', page_name=page)


TypeError: 'page_name' is an invalid keyword argument for this function

I need to pass page_name argument when creating NotebookPage object. But since page_name is not a valid argument of wx.Panel, I get that error.

like image 680
alwbtc Avatar asked Dec 15 '22 02:12

alwbtc


2 Answers

You should remove additional argument from kwargs before calling __init__. For example with dict pop method:

class NotebookPage(wx.Panel):
    def __init__(self, *args, **kwargs):
        page_name = kwargs.pop('page_name', None)
        wx.Panel.__init__(self, *args, **kwargs)
        if page_name:
            # somehow using page_name here
like image 150
ndpu Avatar answered Dec 17 '22 16:12

ndpu


In Python 3.x, you can simply mention the explicit kwarg before the other ones, like this:

class NotebookPage(wx.Panel):
    def __init__(self, *args, page_name, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)
        print(page_name)

In older (2.x) versions of Python, this only works if there are no variable argument lists (*args).

like image 38
phihag Avatar answered Dec 17 '22 14:12

phihag