Search code examples
pythonwebapp2

Who passes *args and **kwargs arguments when a RequestHandler object is instantiated in webapp2 and Python?


I'm using webapp2 and after browsing its source code I still can't figure out how *args and **kwargs arguments are passed to a RequestHandler object.

The code sample I'm looking at looks like this (the actual complete code source is from course-builder and can be found here ):

class ApplicationHandler(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(ApplicationHandler, self).__init__(*args, **kwargs)

Is there a way to know where these are coming from and how to debug them?


Solution

  • *args means 'all positional arguments', and **kwargs means 'all keyword arguments'. The magic of it comes from the little stars (* and **), not the names (actually, it could be any name, for example the same effect would be achieved with *foo and **bar).

    * and ** can be used in any function, not only constructors. The arguments are stored in the variable with the name given after the stars ; for instance, print args will print the list of positional arguments, and print kwargs will display the dictionary of keyword arguments.

    In an inheritance case like the one in your question, it is quite common to call the base class with all the same arguments passed to the subclass constructor.

    ApplicationHandler inherits from webapp2.RequestHandler and in the constructor it is calling the super class (base class) with the super keyword, passing to it all its arguments.

    Let's study this example:

     class A:
       def __init__(self, arg1):
         self.my_value = arg1
    
     class B(A):
       def __init__(self, *args):
         super(B, self).__init__(*args)
    
     b = B("HELLO")
    

    print b.my_value will display HELLO, because arguments passed to the B constructor have been passed to the A constructor in __init__. If you add print args in B.__init__, you will see ("HELLO", ).