Search code examples
pythonselfgoogle-classroompython-class

can I bypass passing self object to a python class method?


I am working with google classroom api and one of the params of a function takes a callback.

def callback(request_id, response, exception):
    if exception is not None:
        print 'Error adding user "{0}" to the course course: {1}'.format(
            request_id, exception)
    else:
        print 'User "{0}" added as a student to the course.'.format(
            response.get('profile').get('name').get('fullName'))

In my case the method is inside a class and as I know every python method should take a self object but in this case this function will have specific params and I am not sure how to pass the self object or should I ignore self? the issue is I plan to use self inside of the function. Any ideas?


Solution

  • I think that I understand your dilema. Go ahead and include self as the first argument, since it will be passed implicitly by Python every time callback() gets called. All the other positional arguments (request_id, response and exception) will not be affected by the inclusion of self in the definition of the method's argument. i.e:

    def callback(self, request_id, response, exception):
        # ...
    

    If you weren't going to use the self object inside the callback method (now a function), then you could use the @staticmethod decorator upon the function's definition, but if I'm following you straight, that's not the case here.

    Edit: If you need to pass a specific parameter without compromising the nature of the callback, you can use partial, from the functools module. I would do something as follows (In this example I'm using the parameter request_id, but it could be any other(s)):

    from functools import partial
    
    partial_callback = partial(callback, request_id='12345')
    

    Now you can pass partial_callback instead of callback wherever you need that specific argument (request_id in my example) to be passed.

    Please note: If you want to pass a parameter that was not defined in the original callback function, that will raise a TypeError. If that was the case, then redefine callback, using the special syntax **kwargs, so that callback now accept a keyworded, variable-length arguments, which will be stored as key-value pairs in a dictionary called kwargs.

    Just note that in order to use the arguments inside the function definition, you must refer to them as kwargs['whatever_argument_name'] (as you would do with any dictionary)

    So, for example, if you want to pass an argument called extraparam, then you would need to have something as follows:

    def callback(self, request_id, response, exception, **kwargs):
        # ...
        extraparam = kwargs.get('extraparam')
        if extraparam is not None:
            # ...
    
    partial_callback = partial(callback, extraparam='whatever')