piiswrong commented on a change in pull request #10833: [WIP] Change class 
variables to thread local variables
URL: https://github.com/apache/incubator-mxnet/pull/10833#discussion_r186498127
 
 

 ##########
 File path: python/mxnet/base.py
 ##########
 @@ -98,6 +99,66 @@ class MXCallbackList(ctypes.Structure):
         ('contexts', ctypes.POINTER(ctypes.c_void_p))
         ]
 
+class ThreadLocalRegistryMeta(type):
+    def __new__(cls, name, parents, dct):
+        if 'local' not in dct:
+            dct['local'] = threading.local()
+        else:
+            raise MXNetError("`local` cannot be used as a class variable name 
when \
+                             using ThreadLocalRegistryMeta metaclass")
+        return super(ThreadLocalRegistryMeta, cls).__new__(cls, name, parents, 
dct)
+
+if sys.version_info[0] < 3:
+    class ThreadLocalRegistry(object):
+        """Structure that holds threadlocal variables and sets context 
manager"""
+        __metaclass__ = ThreadLocalRegistryMeta
+
+        def __init__(self, name):
+            self.old_local = None
+            self.name = name
+
+        def save_local_var(self):
+            self.old_local = getattr(self.__class__.local, self.name, None)
+
+        def load_local_var(self):
+            setattr(self.__class__.local, self.name, self.old_local)
+
+        def set_local_var(self):
+            setattr(self.__class__.local, self.name, self)
+
+        def __enter__(self):
+            self.save_local_var()
+            self.set_local_var()
+            return self
+
+        def __exit__(self, ptype, value, trace):
+            self.load_local_var()
+else:
+    class ThreadLocalRegistry(object, metaclass=ThreadLocalRegistryMeta):
 
 Review comment:
   This looks really complicated. why do you have to use inheritance? Isn't 
composition better?

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services

Reply via email to