title: Thead-safe object and dict types in python
body: <p>I have two questions about creating thread safe types in python, and one related question about multiple inheritance.</p>
  
  <p>1) Are there any problematic implications with using the following subclasses in my threaded application as a sort of "lazy" thread-safe type?  I realize that whomever sets values which may be altered by other threads bears the responsibility to ensure those values are thread safe as well.</p>
  
  <p>2) Another question I have is if there exists more prudent alternatives to these types within python in a typical installation.</p>
  
  <p>Example:</p>
  
  <pre><code>from threading import Lock
  from __future__ import with_statement
  
  class safedict(dict):
      def __init__(self,*args,**kwargs):
          self.mylock=Lock(); 
          super(safedict, self).__init__(*args, **kwargs)
      def __setitem__(self,*args,**kwargs):
          with self.mylock:
              print " DEBUG: Overloaded __setitem__ has the lock now."
              super(safedict,self).__setitem__(*args,**kwargs)
  
  
  class safeobject(object):
      mylock = Lock(); # a temporary useless lock, until we have a proper instance.
      def __init__(self,*args,**kwargs):
          self.mylock=Lock(); 
          super(safeobject, self).__init__(*args, **kwargs)
      def __setattr__(self,*args,**kwargs):
          with self.mylock:
              print " DEBUG: Overloaded __setattr__ has the lock now."
              super(safeobject,self).__setattr__(*args,**kwargs)
  </code></pre>
  
  <p>3) If both of the types defined above could be considered reasonably safe, what negative implications would be faced by using multiple inheritance to create a type that supported a mixture of both of these modifications, and does my example inherit those classes in the optimal order?</p>
  
  <p>Example:</p>
  
  <pre><code>class safedict2(safeobject,dict):
      def __setitem__(self,*args,**kwargs):
          with self.mylock:
              print " DEBUG: Overloaded __setitem__ has the lock now."
              super(safedict2,self).__setitem__(*args,**kwargs)
  </code></pre>
  
  <p>Edit:
  Just another example of another type inheriting both of the former types, and testing using ipython.</p>
  
  <pre><code>In [304]: class safedict3(safeobject,safedict):
     .....:         pass
     .....: 
  
  In [305]: d3 = safedict3()
   DEBUG: Overloaded __setattr__ has the lock now.
   DEBUG: Overloaded __setattr__ has the lock now.
  
  In [306]: d3.a=1
   DEBUG: Overloaded __setattr__ has the lock now.
  
  In [307]: d3['b']=2
   DEBUG: Overloaded __setitem__ has the lock now.
  
  In [308]: d3
  Out[308]: {'b': 2}
  </code></pre>