<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def affinity(self,affinity):
 """Set the affinity for all threads in this group. If setting affinity fails on any thread, the affinity of all threads is restored to its previous value. """

        with self.__lock:
            old_affinities = {}
            try:
                for thread in self.__threads:
                    old_affinities[thread] = thread.affinity
                    thread.affinity = affinity
            except Exception:
                for (thread,old_affinity) in old_affinities.iteritems():
                    try:
                        thread.affinity = old_affinity
                    except Exception:
                        pass
                raise
            else:
                self.__affinity = affinity