Python源码示例:weakref.proxy()
示例1
def __init__(self, path):
package_name = '_jinja2_module_templates_%x' % id(self)
# create a fake module that looks for the templates in the
# path given.
mod = _TemplateModule(package_name)
if isinstance(path, string_types):
path = [path]
else:
path = list(path)
mod.__path__ = path
sys.modules[package_name] = weakref.proxy(mod,
lambda x: sys.modules.pop(package_name, None))
# the only strong reference, the sys.modules entry is weak
# so that the garbage collector can remove it once the
# loader that created it goes out of business.
self.module = mod
self.package_name = package_name
示例2
def __init__(self, *args, **kwds):
'''Initialize an ordered dictionary. The signature is the same as
regular dictionaries, but keyword arguments are not recommended because
their insertion order is arbitrary.
'''
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__root
except AttributeError:
self.__hardroot = _Link()
self.__root = root = _proxy(self.__hardroot)
root.prev = root.next = root
self.__map = {}
self.__update(*args, **kwds)
示例3
def __init__(self, path):
package_name = '_jinja2_module_templates_%x' % id(self)
# create a fake module that looks for the templates in the
# path given.
mod = _TemplateModule(package_name)
if isinstance(path, string_types):
path = [path]
else:
path = list(path)
mod.__path__ = path
sys.modules[package_name] = weakref.proxy(mod,
lambda x: sys.modules.pop(package_name, None))
# the only strong reference, the sys.modules entry is weak
# so that the garbage collector can remove it once the
# loader that created it goes out of business.
self.module = mod
self.package_name = package_name
示例4
def __init__(self, path):
package_name = '_jinja2_module_templates_%x' % id(self)
# create a fake module that looks for the templates in the
# path given.
mod = _TemplateModule(package_name)
if isinstance(path, string_types):
path = [path]
else:
path = list(path)
mod.__path__ = path
sys.modules[package_name] = weakref.proxy(mod,
lambda x: sys.modules.pop(package_name, None))
# the only strong reference, the sys.modules entry is weak
# so that the garbage collector can remove it once the
# loader that created it goes out of business.
self.module = mod
self.package_name = package_name
示例5
def __init__(self, path):
package_name = '_jinja2_module_templates_%x' % id(self)
# create a fake module that looks for the templates in the
# path given.
mod = _TemplateModule(package_name)
if isinstance(path, string_types):
path = [path]
else:
path = list(path)
mod.__path__ = path
sys.modules[package_name] = weakref.proxy(mod,
lambda x: sys.modules.pop(package_name, None))
# the only strong reference, the sys.modules entry is weak
# so that the garbage collector can remove it once the
# loader that created it goes out of business.
self.module = mod
self.package_name = package_name
示例6
def __init__(self, connection):
"""Initialize"""
MySQLCursorAbstract.__init__(self)
self._insert_id = 0
self._warning_count = 0
self._warnings = None
self._affected_rows = -1
self._rowcount = -1
self._nextrow = None
self._executed = None
self._executed_list = []
self._stored_results = []
if not isinstance(connection, MySQLConnectionAbstract):
raise errors.InterfaceError(errno=2048)
self._cnx = weakref.proxy(connection)
示例7
def __init__(self, protocol, _type, _id, name="World Server 1", _max=300, server_protocol = AS3_PROTOCOL):
self.protocol = protocol
self.server_protocol = server_protocol
self.type = _type
self.id = _id
self.logger = logging.getLogger(TIMELINE_LOGGER)
self.name = name
self.users = deque() # Thread safe
self.dbDetails = dict()
self.maximum = _max - 1
self._listening = False
self._portListener = None
self.proxyReference = weakref.proxy(self)
self.redis = Redis(self)
self.log("info", "Timeline Factory Started!")
self.log("info", "Running:", self.name)
self.log("info", "Maximum users:", self.maximum)
if self.type == WORLD_SERVER:
self.initializeWorld()
self.redis.redisConnectionDefer.addCallback(lambda *x: GeneralEvent('onEngine', self))
示例8
def buildPenguin(self):
self.handshakeStage = -1
self.canRecvPacket = False
self.ReceivePacketEnabled = True # Penguin can receive packet only if both this and self.canRecvPacket is true.
# Some XT packets are sent before J#JS to make sure client is alive, just to make sure to ignore it ;)
# ('category', 'handler', 0 or 1 : execute : don't execute)
self.ignorableXTPackets = [('s', 'j#js', 1), ('s', 'p#getdigcooldown', 0), ('s', 'u#h', 0), ('s', 'f#epfgf', 0), ('l', 'login', 1)]
self.penguin = PenguinObject()
self.penguin.name = None
self.penguin.id = None
self.penguin.room = None
self.penguin.prevRooms = list()
self.ref = weakref.proxy(self)
# Initiate Packet Handler
self.PacketHandler = PacketHandler(self.ref)
self.CryptoHandler = Crypto(self.ref)
示例9
def __init__(self, path):
package_name = '_jinja2_module_templates_%x' % id(self)
# create a fake module that looks for the templates in the
# path given.
mod = _TemplateModule(package_name)
if isinstance(path, string_types):
path = [path]
else:
path = list(path)
mod.__path__ = path
sys.modules[package_name] = weakref.proxy(mod,
lambda x: sys.modules.pop(package_name, None))
# the only strong reference, the sys.modules entry is weak
# so that the garbage collector can remove it once the
# loader that created it goes out of business.
self.module = mod
self.package_name = package_name
示例10
def __init__(
self, ds,
fp, dtype, channel_count, channels_schema, sr,
compute_array, merge_arrays,
cache_dir, overwrite,
primitives_back, primitives_kwargs, convert_footprint_per_primitive,
computation_pool, merge_pool, io_pool, resample_pool,
cache_tiles, computation_tiles,
max_resampling_size,
debug_observers,
):
back = BackCachedRasterRecipe(
ds._back,
weakref.proxy(self),
fp, dtype, channel_count, channels_schema, sr,
compute_array, merge_arrays,
cache_dir, overwrite,
primitives_back, primitives_kwargs, convert_footprint_per_primitive,
computation_pool, merge_pool, io_pool, resample_pool,
cache_tiles, computation_tiles,
max_resampling_size,
debug_observers,
)
super().__init__(ds=ds, back=back)
示例11
def __init__(self, max_size=10, kill_cb=None, lock=False):
"""Constructor.
Args:
max_size: The maximum number of objects held in cache.
kill_cb: An optional function which will be called on each
object terminated from cache.
lock: If True this cache will be thread safe.
"""
self._age = LinkedList()
self._hash = {}
self._limit = max_size
self._kill_cb = kill_cb
self.lock = None
if lock:
self.lock = threading.RLock()
self.hits = self.misses = 0
self.creator = GetStack()
self.STORES[id(self)] = weakref.proxy(
self, lambda _, id=id(self), s=self.STORES: s.pop(id))
示例12
def logging(self):
if self.logger is not None:
return self.logger
logger_name = u"rekall.%s" % self.session_id
if self._logger is None or self._logger.name != logger_name:
# Set up a logging object. All rekall logging must be done
# through the session's logger.
self._logger = logging.getLogger(logger_name)
# A special log handler that hoards all messages until there's a
# renderer that can transport them.
self._log_handler = HoardingLogHandler()
# Since the logger is a global it must not hold a permanent
# reference to the HoardingLogHandler, otherwise we may never be
# collected.
def Remove(_, l=self._log_handler):
l.handlers = []
self._logger.addHandler(weakref.proxy(
self._log_handler, Remove))
return self._logger
示例13
def __init__(self, application, window):
utilities.assert_arg_type(application, Gtk.Application, arg_pos=1)
utilities.assert_arg_type(window, MainAppWindow, arg_pos=2)
super(MainMenuBar, self).__init__(application)
self.window = weakref.proxy(window)
self._add_accelerators()
graphs_menu_item = self.gtk_builder_get('menuitem_tools_create_graph')
if graphs.has_matplotlib:
graphs_submenu = Gtk.Menu.new()
for graph_name in graphs.get_graphs():
graph = graphs.get_graph(graph_name)
menu_item = Gtk.MenuItem.new_with_label(graph.name_human)
menu_item.connect('activate', self.signal_activate_tools_show_campaign_graph, graph_name)
graphs_submenu.append(menu_item)
graphs_menu_item.set_submenu(graphs_submenu)
graphs_menu_item.show_all()
else:
graphs_menu_item.set_sensitive(False)
示例14
def __init__(self, parent_message):
"""Args:
parent_message: The message whose _Modified() method we should call when
we receive Modified() messages.
"""
# This listener establishes a back reference from a child (contained) object
# to its parent (containing) object. We make this a weak reference to avoid
# creating cyclic garbage when the client finishes with the 'parent' object
# in the tree.
if isinstance(parent_message, weakref.ProxyType):
self._parent_message_weakref = parent_message
else:
self._parent_message_weakref = weakref.proxy(parent_message)
# As an optimization, we also indicate directly on the listener whether
# or not the parent message is dirty. This way we can avoid traversing
# up the tree in the common case.
self.dirty = False
示例15
def test_ref_reuse(self):
o = C()
ref1 = weakref.ref(o)
# create a proxy to make sure that there's an intervening creation
# between these two; it should make no difference
proxy = weakref.proxy(o)
ref2 = weakref.ref(o)
self.assertIs(ref1, ref2,
"reference object w/out callback should be re-used")
o = C()
proxy = weakref.proxy(o)
ref1 = weakref.ref(o)
ref2 = weakref.ref(o)
self.assertIs(ref1, ref2,
"reference object w/out callback should be re-used")
self.assertEqual(weakref.getweakrefcount(o), 2,
"wrong weak ref count for object")
del proxy
self.assertEqual(weakref.getweakrefcount(o), 1,
"wrong weak ref count for object after deleting proxy")
示例16
def test_proxy_div(self):
class C:
def __floordiv__(self, other):
return 42
def __ifloordiv__(self, other):
return 21
o = C()
p = weakref.proxy(o)
self.assertEqual(p // 5, 42)
p //= 5
self.assertEqual(p, 21)
# The PyWeakref_* C API is documented as allowing either NULL or
# None as the value for the callback, where either means "no
# callback". The "no callback" ref and proxy objects are supposed
# to be shared so long as they exist by all callers so long as
# they are active. In Python 2.3.3 and earlier, this guarantee
# was not honored, and was broken in different ways for
# PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
示例17
def test_callable_proxy(self):
o = Callable()
ref1 = weakref.proxy(o)
self.check_proxy(o, ref1)
self.assertIs(type(ref1), weakref.CallableProxyType,
"proxy is not of callable type")
ref1('twinkies!')
self.assertEqual(o.bar, 'twinkies!',
"call through proxy not passed through to original")
ref1(x='Splat.')
self.assertEqual(o.bar, 'Splat.',
"call through proxy not passed through to original")
# expect due to too few args
self.assertRaises(TypeError, ref1)
# expect due to too many args
self.assertRaises(TypeError, ref1, 1, 2, 3)
示例18
def check_proxy(self, o, proxy):
o.foo = 1
self.assertEqual(proxy.foo, 1,
"proxy does not reflect attribute addition")
o.foo = 2
self.assertEqual(proxy.foo, 2,
"proxy does not reflect attribute modification")
del o.foo
self.assertFalse(hasattr(proxy, 'foo'),
"proxy does not reflect attribute removal")
proxy.foo = 1
self.assertEqual(o.foo, 1,
"object does not reflect attribute addition via proxy")
proxy.foo = 2
self.assertEqual(o.foo, 2,
"object does not reflect attribute modification via proxy")
del proxy.foo
self.assertFalse(hasattr(o, 'foo'),
"object does not reflect attribute removal via proxy")
示例19
def test_getweakrefcount(self):
o = C()
ref1 = weakref.ref(o)
ref2 = weakref.ref(o, self.callback)
self.assertEqual(weakref.getweakrefcount(o), 2,
"got wrong number of weak reference objects")
proxy1 = weakref.proxy(o)
proxy2 = weakref.proxy(o, self.callback)
self.assertEqual(weakref.getweakrefcount(o), 4,
"got wrong number of weak reference objects")
del ref1, ref2, proxy1, proxy2
self.assertEqual(weakref.getweakrefcount(o), 0,
"weak reference objects not unlinked from"
" referent when discarded.")
# assumes ints do not support weakrefs
self.assertEqual(weakref.getweakrefcount(1), 0,
"got wrong number of weak reference objects for int")
示例20
def __copy__(self):
raise NotImplementedError('object proxy must define __copy__()')
示例21
def __deepcopy__(self, memo):
raise NotImplementedError('object proxy must define __deepcopy__()')
示例22
def __reduce__(self):
raise NotImplementedError(
'object proxy must define __reduce_ex__()')
示例23
def __reduce_ex__(self, protocol):
raise NotImplementedError(
'object proxy must define __reduce_ex__()')
示例24
def wrap_object(module, name, factory, args=(), kwargs={}):
(parent, attribute, original) = resolve_path(module, name)
wrapper = factory(original, *args, **kwargs)
apply_patch(parent, attribute, wrapper)
return wrapper
# Function for applying a proxy object to an attribute of a class
# instance. The wrapper works by defining an attribute of the same name
# on the class which is a descriptor and which intercepts access to the
# instance attribute. Note that this cannot be used on attributes which
# are themselves defined by a property object.
示例25
def _weak_function_proxy_callback(ref, proxy, callback):
if proxy._self_expired:
return
proxy._self_expired = True
# This could raise an exception. We let it propagate back and let
# the weakref.proxy() deal with it, at which point it generally
# prints out a short error message direct to stderr and keeps going.
if callback is not None:
callback(proxy)
示例26
def __setitem__(self, key, value,
dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link at the end of the linked list,
# and the inherited dictionary is updated with the new key/value pair.
if key not in self:
self.__map[key] = link = Link()
root = self.__root
last = root.prev
link.prev, link.next, link.key = last, root, key
last.next = link
root.prev = proxy(link)
dict_setitem(self, key, value)
示例27
def wrap_object(module, name, factory, args=(), kwargs={}):
(parent, attribute, original) = resolve_path(module, name)
wrapper = factory(original, *args, **kwargs)
apply_patch(parent, attribute, wrapper)
return wrapper
# Function for applying a proxy object to an attribute of a class
# instance. The wrapper works by defining an attribute of the same name
# on the class which is a descriptor and which intercepts access to the
# instance attribute. Note that this cannot be used on attributes which
# are themselves defined by a property object.
示例28
def transient_function_wrapper(module, name):
def _decorator(wrapper):
def _wrapper(wrapped, instance, args, kwargs):
target_wrapped = args[0]
if instance is None:
target_wrapper = wrapper
elif inspect.isclass(instance):
target_wrapper = wrapper.__get__(None, instance)
else:
target_wrapper = wrapper.__get__(instance, type(instance))
def _execute(wrapped, instance, args, kwargs):
(parent, attribute, original) = resolve_path(module, name)
replacement = FunctionWrapper(original, target_wrapper)
setattr(parent, attribute, replacement)
try:
return wrapped(*args, **kwargs)
finally:
setattr(parent, attribute, original)
return FunctionWrapper(target_wrapped, _execute)
return FunctionWrapper(wrapper, _wrapper)
return _decorator
# A weak function proxy. This will work on instance methods, class
# methods, static methods and regular functions. Special treatment is
# needed for the method types because the bound method is effectively a
# transient object and applying a weak reference to one will immediately
# result in it being destroyed and the weakref callback called. The weak
# reference is therefore applied to the instance the method is bound to
# and the original function. The function is then rebound at the point
# of a call via the weak function proxy.
示例29
def _weak_function_proxy_callback(ref, proxy, callback):
if proxy._self_expired:
return
proxy._self_expired = True
# This could raise an exception. We let it propagate back and let
# the weakref.proxy() deal with it, at which point it generally
# prints out a short error message direct to stderr and keeps going.
if callback is not None:
callback(proxy)
示例30
def __init__(self, obj):
# Use weakref to make NpzFile objects collectable by refcount
self._obj = weakref.proxy(obj)