Search code examples
pythonkeyword-argument

how to pass **kwargs to a function from a class method


I need to create a custom transformer class for a machine learning pipeline. The testfun is actually an R function accessed through rpy2. testfun is then used inside the test class. I want to expose all arguments of the R function represented by testfun, hence **kwargs. But I don't know how to pass **kwargs. Code below throws an error.

def testfun(x=1, a=1, b=1, c=1):
    return x**a, b**c

class test(BaseEstimator, TransformerMixin):
    def __init__(self, **kwargs):
        self.__dict__.update(**kwargs)
    def testkwargs(self):
        return testfun(**kwargs)
temp = test(x=1,a=1,b=2,c=3)
temp.testkwargs()

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-131-de41ca28c280> in <module>
      5         return testfun(**kwargs)
      6 temp = test(x=1,a=1,b=2,c=3)
----> 7 temp.testkwargs()

<ipython-input-131-de41ca28c280> in testkwargs(self)
      3         self.__dict__.update(**kwargs)
      4     def testkwargs(self):
----> 5         return testfun(**kwargs)
      6 temp = test(x=1,a=1,b=2,c=3)
      7 temp.testkwargs()

NameError: name 'kwargs' is not defined

Thanks in advance!

EDIT: changes according to early suggestions didn't help much

class test(BaseEstimator, TransformerMixin):
    def __init__(self, **kwargs):
        self.__dict__.update(**kwargs)
    def testkwargs(self, **kwargs):
        return testfun(**kwargs)
temp = test(x=2,a=1,b=2,c=3)
temp.testkwargs()

Output:

 (1, 1)

Solution

  • Here you can do this way.

    def testfun(x=1, a=1, b=1, c=1):
        return x**a, b**c
    
    class test():
        def __init__(self, **kwargs):
            self.__dict__.update(**kwargs)
            self.kwargs = kwargs
        def testkwargs(self):
            return testfun(**self.kwargs)
    
    temp = test(x=1,a=1,b=2,c=3)
    temp.testkwargs()