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)
Unexpected keyword argument %r in %s call. Description: Used when a function call passes a keyword argument that doesn't correspond to one of the function's parameter names.
Using Positional Arguments Followed by Keyword Arguments One method is to simply do what the error states and specify all positional arguments before our keyword arguments! Here, we use the positional argument 1 followed by the keyword argument num2=2 which fixes the error.
In this article, we learned about two special keywords in Python – *args and **kwargs . These make a Python function flexible so it can accept a variable number of arguments and keyword arguments, respectively.
Use a try/except block to ignore a KeyError exception in Python. The except block is only going to run if a KeyError exception was raised in the try block. You can use the pass keyword to ignore the exception.
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):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With