def __throw(self): generics = self.generics while isinstance(generics, Closure): generics = generics() if inspect.ismodule(generics): name = '__THROW__' elif inspect.isclass(generics): name = '__Throw__' else: name = '__throw__' assert hasvar(generics, name) or setvar(generics, name, set()) return getvar(generics, name)
def __lock(self): generics = self.generics k = self.k while isinstance(generics, Closure): generics = generics() if inspect.ismodule(generics): name = '__LOCK__' elif inspect.isclass(generics): name = '__Lock__' else: name = '__lock__' with Lock.LOCK: assert hasvar(generics, name) or setvar(generics, name, dict()) var = getvar(generics, name) if k not in var: var[k] = threading.RLock() return var[k]
def __new__(mcls, *args, **kwargs): if mcls is __class__: sid = pickle.dumps(( args, sorted(kwargs.items(), key=lambda i: i[0]), )) with Lock(instance): assert hasvar(instance, '__instance__') or setvar( instance, '__instance__', dict()) INSTANCES = getvar(instance, '__instance__') if cid not in INSTANCES: INSTANCES[cid] = dict() instances = INSTANCES[cid] if sid not in instances: instances[sid] = super_new(mcls)(mcls, *args, **kwargs) return instances[sid] else: return super_new(mcls)(mcls, *args, **kwargs)
def Cursor(connect): assert hasvar(connect, '_cursors') or setvar(connect, '_cursors', set()) var = getvar(connect, '_cursors') cursor = connect.cursor(cursor=pymysql.cursors.DictCursor) var.add(cursor) try: yield cursor except BaseException: var.remove(cursor) if not var: connect.rollback() cursor.close() raise else: var.remove(cursor) if not var: connect.commit() cursor.close()
def __init__(self, *args, **kwargs): if type(self) is __class__: with Lock(self): with Lock(instance): instances = getvar(instance, '__instance__')[cid] assert self in instances.values() try: assert hasvar(self, '__old__') or setvar( self, '__old__', super_init(self)(*args, **kwargs)) return getvar(self, '__old__') except BaseException: with Lock(instance): for k in tuple(instances.keys()): if instances[k] is self: del instances[k] raise else: return super_init(self)(*args, **kwargs)