title: Thread Safe Python Property/Attribute?
body: <p>I have code like the following:</p>
  
  <pre><code>class SomeSharedData(object):
      def __init__(self):
          self._lock = RLock()
          self._errors = 0
  
      @property
      def errors(self):
          with self._lock:
          return self._errors
  
      @errors.setter
      def errors(self, value):
          with self._lock:
              self._errors = value
  </code></pre>
  
  <p>Except with more properties like <code>errors</code>. My goal here is ease-of-use, and not efficiency, so the excessive locking is fine.</p>
  
  <p><strong>Is there a more concise way of defining these properties?</strong></p>
  
  <p>The best I've come up with so far is this:</p>
  
  <pre><code>class thread_safe_property(object):
      def __init__(self, name=None):
          self.name = name
  
      def __get__(self, obj, objtype):
          with obj._lock:
              return getattr(obj, self.name)
  
      def __set__(self, obj, val):
          with obj._lock:
              setattr(obj, self.name, val)
  
  class SomeSharedData(object):
      def __init__(self):
          self._lock = RLock()
          self._errors = 0
  
      errors = thread_safe_property('_errors')
  </code></pre>
  
  <p><strong>Ideas? Better Ways?</strong></p>
  
  <p>Both the original code and the new approach suffer from possible race conditions on statements like <code>data.errors += 1</code>, but I rarely need to perform those operations so I add workarounds where needed.</p>
  
  <p>Thank you!</p>