title: python: elegant way to deal with lock on a variable?
body: <p>I have code that looks like something like this:</p>
  
  <pre><code>def startSearching(self):
      self.searchingLock.acquire()
      searching = self.searching
      if self.searching:
          self.searchingLock.release()
          self.logger.error("Already searching!")
          return False
  
      self.searching = True
      self.searchingLock.release()
  
      #some more init code, then start the thread which
      #constantly checks self.searching to determine when to stop
  </code></pre>
  
  <p>it's kind of ugly, though. lots of acquires and releases. this looks prettier:</p>
  
  <pre><code>def startSearching(self):
      with self.searchingLock:
          if self.searching:
              self.logger.error("Already searching!")
              return False
  
          self.searching = True
  
      #some more init code, then start the thread which
      #constantly checks self.searching to determine when to stop
  </code></pre>
  
  <p>but this keeps the lock longer than strictly necessary, espcially if <code>self.logger.error</code> takes a while (like if it writes to disk, which it does). is there any middle ground between holding the lock as little as possible but having prettier code?</p>