Leopd
Leopd

Reputation: 42757

Unexpected keyword argument when using **kwargs in constructor

I'm baffled. I'm trying to make a subclass that doesn't care about any keyword parameters -- just passes them all along as is to the superclass, and explicitly sets the one parameter that is required for the constructor. Here's a simplified version of my code:

class BaseClass(object):
    def __init__(self, required, optional=None):
        pass

def SubClass(BaseClass):
    def __init__(self, **kwargs):
        super(SubClass, self).__init__(None, **kwargs)

a = SubClass(optional='foo')  # this throws TypeError!?!??

This fails with

leo@loki$ python minimal.py
Traceback (most recent call last):
  File "minimal.py", line 9, in <module>
    a = SubClass(optional='foo')
TypeError: SubClass() got an unexpected keyword argument 'optional'

How can it complain about an unexpected keyword argument when the method has **kwargs?

(Python 2.7.3 on Ubuntu)

Upvotes: 15

Views: 7036

Answers (2)

ConnectedSystems
ConnectedSystems

Reputation: 932

Stumbled on to this post when searching for an answer to the exact same error, but different cause.

I worked out my problem (python beginners mistake), but thought I should put it up here in case it helps someone else.

My project structure:

project\
--package1\
----Module1.py
----Module2.py
--package2\
...blah blah blah...

where Module2 extends Module1, and class names were the same as the module/file names

In Module2.py, I had:

from package1 import Module1

assuming that this would import the classes within.

Received an unexpected keyword argument error when I tried to create Module2 Class

Mod2 = Module2(kw1=var1, kw2=var2)

Fixed by using

from package1.Module1 import Module1

That is [package name].[module name] import [class name]

Hope this helps someone else out there

Upvotes: 2

Ry-
Ry-

Reputation: 224963

def SubClass(BaseClass):

is a function, not a class. There's no error because BaseClass could be an argument name, and nested functions are allowed. Syntax is fun, isn't it?

class SubClass(BaseClass):

Upvotes: 20

Related Questions