Python Conditional “With” Lock Design

后端 未结 5 1990
孤独总比滥情好
孤独总比滥情好 2020-12-15 16:48

I am trying to do some shared locking using with statements

def someMethod(self, hasLock = False):
     with self.my_lock:
         self.somethingElse(hasLoc         


        
5条回答
  •  猫巷女王i
    2020-12-15 17:35

    The Python or is short circuiting so you can make the locking conditional:

    def somethingElse(self, hasLock = False):
        #I want this to be conditional...
        with hasLock or self.my_lock:
              print 'i hate hello worlds'
    

    Unfortunately it's not quite that easy, because a boolean isn't a valid return from a with statement. You'll need to create a class with the __enter__ and __exit__ to wrap the boolean True value.

    Here's one possible implementation that I haven't tested.

    from contextlib import contextmanager
    
    @contextmanager
    def withTrue():
        yield True
    
    def withbool(condition):
        if condition:
            return withTrue()
        return False
    
    def somethingElse(self, hasLock = False):
        with withbool(hasLock) or self.my_lock():
              print 'i hate hello worlds'
    

    This is a lot of boilerplate for something so simple, so the RLock solution looks like a winner. This solution might be useful in a different context though.

提交回复
热议问题