CHINTAN VADGAMA
CHINTAN VADGAMA

Reputation: 724

How to check a condition for every instance method of class?

I want to check for an if condition whenever an instance method of a class is called.

For example,we have constructor classes that have lots of attributes those are used in payload construct methods but they also have payload attribute in which user can pass payload dictionary that can be used directly whenever API request is called.

For each payload construction function, we have to check at the start of function that

if object.payload:
   return object.payload
else:
   # construct the payload using other instance variables 
""" Each constructor class has payload attribute """
class X:
    """ This is a constructor class to represent X object """
    def __init__(self, payload=None):
        self.payload = payload

class Y:
    """ This is a constructor class to represent Y object """
    def __init__(self, payload=None):
        self.payload = payload

class CreatePayload:
    def __init__(self, api):
        self.api = api
    
    def create_json_for_x(self, object_x):
        if object_x.payload:
           return object_x.payload
        payload = {
                   "val" : object_x.val
                  }
        return payload

    def create_json_for_y(self, object_y):
        if object_y.payload:
           return object_y.payload
        payload = {
                     "val" : object_y.val,
                     "user" : object_y.user
                  }
        return payload

    def create_x(self, object_x):
        uri = "/test_x"
        payload = create_json_for_x(object_x)
        # send_request method sends a HTTP GET/PUT/POST/DELETE requests
        request = self.api.send_request(uri, 'post', payload)
        return request

     

    

I want to have a solution using decorator or Metaclass which takes the object as input and always check if it has the payload attribute then return the payload value.

Upvotes: 0

Views: 352

Answers (1)

Bharel
Bharel

Reputation: 26971

Will something like this do the job?

from functools import wraps
def return_payload(func):
    @wraps(func)
    def wrapped(self, obj, *args, **kwargs):
        if obj.payload:
            return obj.payload
        return func(self, obj, *args, **kwargs)
    return wrapped

class CreatePayload:
    def __init__(self, api):
        self.api = api
    
    @return_payload
    def create_json_for_x(self, object_x):
        payload = {
                   "val" : object_x.val
                  }
        return payload

Upvotes: 1

Related Questions