Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: cleanest way to wrap each method in parent class in a "with"

I have a parent class that has a bunch of class methods:

class Parent():

    @classmethod
    def methodA(cls):
        pass

    @classmethod
    def methodB(cls):
        pass

In my subclass, I would like to wrap a subset of the methods inside a "with". It should achieve this effect:

class Child(Parent):

    @classmethod
    def methodA(cls):
        with db.transaction:
            super(Child, cls).methodA()

I have a bunch of methods that follow this pattern and would prefer not to repeat myself. Is there a cleaner way to do this?

like image 343
stackOverlord Avatar asked Jan 21 '12 21:01

stackOverlord


1 Answers

It seems you should move the with db.transaction into the base. Make a method in the base, returning the db.transaction

@staticmethod
def gettransaction(): return db.transaction

then you overload it in the children as/if needed.

In the base you then do

  def methodB(cls):
    with cls.gettransaction():
       bla ...

Here's a complete working example with a dummy transaction

class transact:
    def __enter__(a): 
        print "enter"
    def __exit__(a,b,c,d): 
        print "exit"

class transact2:
    def __enter__(a): 
        print "enter2"
    def __exit__(a,b,c,d): 
        print "exit2"

class Parent():
    @staticmethod
    def gettrans(): 
        return transact()
    def methodA(cl):
        with cl.gettrans(): 
            print "A"

class Child(Parent): 
    pass
    @staticmethod
    def gettrans(): 
        return transact2()

p=Parent()
p.methodA()
c=Child()  
c.methodA()

this results in

enter
A
exit
enter2
A
exit2
like image 142
Johan Lundberg Avatar answered Oct 06 '22 15:10

Johan Lundberg