pythonargskeyword-argumentvtk.js

Double check about Arbitrary Keyword Arguments in Python


I'm quite new to Python and I'm studing an opensource framework written in Python. I'm trying to dive a little bit deeper in the source code. I can't understand why the "Arbitrary Arguments" and "Arbitrary Keyword Arguments" are required in this line of code:

observerCallback = lambda *args, **kwargs: self.pushRender(realViewId)

basically because, at the end, they are not used in the "called" method:

def pushRender(self, vId, ignoreAnimation = False):
    ...

So, once again: what is the purpose of using *args and **kwargs here? I know it could looks like a silly question, but I just learnt right now meaning of this "special operators" and my brain is almost out of work after days spent on exploring this source code. If someone can help me understand a little bit better, for sure I really appreciate that.

enter image description here


Solution

  • The caller of observerCallback is probably passing some arguments to the function, so the function needs to accept them. Otherwise this would happen:

    >>> observerCallback = lambda: self.pushRender(realViewId)
    >>> observerCallback('foo', bar='baz')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: <lambda>() got an unexpected keyword argument 'bar'
    

    This particular observerCallback simply chooses to ignore/not use any passed arguments. By convention you should use _ instead of "args" and "kwargs" as an indicator that you're going to disregard those arguments:

    lambda *_, **__: ...