Anurag Sharma
Anurag Sharma

Reputation: 5039

passing class variables to decorator

I have a class like this

class BusinessLogic(object):
def __init__(self):
    self.url_context = None
    self.attribute_info = None
    self.current_data = None

def __nonzero__(self):
    if self.url_context and self.current_data:
        return True
    return False

def clean_up(self):
    self.url_context = None
    self.current_data = None

def set_current_info(self, url_context, data):
    self.url_context = url_context
    self.current_data = sku_data

def handle_secondary_id(self):
    try:
        orig_data = copy.deep_copy(self.current_data)
        keep_secondary_id = self.url_context.layout.get('Secondary_Id', False)
        if not keep_secondary_id and ATTRIBUTE_SECONDARY_ID in self.current_data.attributes:
            del self.current_data.attributes[ATTRIBUTE_SECONDARY_ID]
    except Exception, e:
        print "Error!!!"
        self.current_data = orig_data

def process_sku(self):
    if self:
        self.handle_secondary_id()
        # Can have multiple functions below
        #self.handle_other_attributes()
    return self.current_sku_data

Basically in my handle_secondary_id function I made a deep-copy of my current_data in orig_data, perform some operations and if the operation failed in middle than I copy orig_data to current_data. I have to perform similar thing in other function like handle_other_attributes and so on.

So the idea is to perform series of operation on self.current_data and saving the intermediate result, in case any one of the operation fails copy the previous saved state to the current_data and continue. But I want to avoid writing try: except: block. I was thinking of writing a decorator for it, by passing BussinessLogic object to the decorator, but I am not sure how to do that

Upvotes: 3

Views: 256

Answers (1)

Adi Levin
Adi Levin

Reputation: 5233

self is just an argument that is sent to the method. You can capture it in your decorator wrapper function as follows:

def MyDecorator(f):
    def wrapper(*args):
        print args[0].x
        return f(*args)
    return wrapper

class C(object):
    def __init__(self):
        self.x = 1
    @MyDecorator
    def do(self):
        print 'do'

c = C()
c.do()

Yields

1
do

Upvotes: 2

Related Questions