Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected keyword argument when using **kwargs in constructor

Tags:

python

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)

like image 961
Leopd Avatar asked Dec 16 '12 01:12

Leopd


People also ask

What is unexpected keyword argument?

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.

How do you fix Syntaxerror positional argument follows keyword argument?

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.

Is Kwargs a keyword?

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.

How do you ignore a keyword in Python?

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.


1 Answers

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):
like image 84
Ry- Avatar answered Oct 05 '22 02:10

Ry-