Skip to content

Instantly share code, notes, and snippets.

@oglops
Last active May 12, 2017
Embed
What would you like to do?
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