Skip to content

Instantly share code, notes, and snippets.

@oglops
Last active May 12, 2017 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oglops/35b9edcf22f50cc3026ee3150c15b5f6 to your computer and use it in GitHub Desktop.
Save oglops/35b9edcf22f50cc3026ee3150c15b5f6 to your computer and use it in GitHub Desktop.
context aware context decorator for maya
#!/usr/bin/env python
from abc import ABCMeta, abstractmethod
from functools import wraps
import time
class Singleton(ABCMeta):
_instance = None
def __call__(cls, *args, **kwargs):
if not hasattr(cls, "_instance") or cls._instance is None:
cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instance
class ContextDecorator(object):
__metaclass__ = Singleton
def __init__(self, *args, **kwargs):
self.args = args
self.__dict__.update(kwargs)
self._built = False
self._contextExists = False
self._rebuild = kwargs.get('rebuild', False)
@abstractmethod
def _build(self):
pass
@abstractmethod
def _destroy(self):
pass
@classmethod
def clear_singleton(cls):
cls._instance = None
def __enter__(self):
if not self._built or self._rebuild:
self._build()
self._built = True
print 'call _build first time'
else:
print 'skip _build'
self._contextExists = True
return self
def __exit__(self, typ, val, traceback):
if not self._contextExists or self._rebuild:
self._destroy()
self.clear_singleton()
# self._contextExists=False
print 'call _destroy first time'
else:
print 'skip _destroy'
self._contextExists = False
def __call__(self, f):
self.function = f
@wraps(f)
def wrapper(*args, **kw):
with self:
try:
return f(*args, **kw)
except:
raise
return wrapper
class CustomContext(ContextDecorator):
def __init__(self, *args, **kwargs):
super(CustomContext, self).__init__(*args, **kwargs)
def _build(self):
pass
def _destroy(self):
pass
print 'context manager test'
with CustomContext():
for i in range(3):
with CustomContext():
time.sleep(0.01)
print '-' * 10
print 'decorator test'
@CustomContext()
@CustomContext()
def test():
print 'inside test func'
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment