本文整理汇总了Python中weakref.ReferenceType方法的典型用法代码示例。如果您正苦于以下问题:Python weakref.ReferenceType方法的具体用法?Python weakref.ReferenceType怎么用?Python weakref.ReferenceType使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类weakref
的用法示例。
在下文中一共展示了weakref.ReferenceType方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: base_equal
# 需要导入模块: import weakref [as 别名]
# 或者: from weakref import ReferenceType [as 别名]
def base_equal(self, ob1, ob2):
if type(ob1) != type(ob2):
return False
def cmp(obj1, obj2):
if isinstance(obj1, np.ndarray):
return np.array_equal(obj1, obj2)
elif isinstance(obj1, Iterable) and \
not isinstance(obj1, str) and \
isinstance(obj2, Iterable) and \
not isinstance(obj2, str):
return all(cmp(it1, it2) for it1, it2 in itertools.zip_longest(obj1, obj2))
elif hasattr(obj1, 'key') and hasattr(obj2, 'key'):
return obj1.key == obj2.key
elif isinstance(obj1, ReferenceType) and isinstance(obj2, ReferenceType):
return cmp(obj1(), obj2())
else:
return obj1 == obj2
for slot in ob1.__slots__:
if not cmp(getattr(ob1, slot, None), getattr(ob2, slot, None)):
return False
return True
示例2: test_gc
# 需要导入模块: import weakref [as 别名]
# 或者: from weakref import ReferenceType [as 别名]
def test_gc(self):
# Github issue 1769: Runner objects can get GCed unexpectedly
# while their future is alive.
weakref_scope = [None] # type: List[Optional[weakref.ReferenceType]]
def callback():
gc.collect(2)
weakref_scope[0]().set_result(123) # type: ignore
@gen.coroutine
def tester():
fut = Future() # type: Future[int]
weakref_scope[0] = weakref.ref(fut)
self.io_loop.add_callback(callback)
yield fut
yield gen.with_timeout(datetime.timedelta(seconds=0.2), tester())
示例3: __init__
# 需要导入模块: import weakref [as 别名]
# 或者: from weakref import ReferenceType [as 别名]
def __init__(
self,
*,
path_id: Optional[pathid.PathId]=None,
fenced: bool=False,
unique_id: Optional[int]=None,
) -> None:
self.unique_id = unique_id
self.path_id = path_id
self.fenced = fenced
self.protect_parent = False
self.unnest_fence = False
self.factoring_fence = False
self.factoring_whitelist = set()
self.optional = False
self.children = set()
self.namespaces = set()
self._parent: Optional[weakref.ReferenceType[ScopeTreeNode]] = None
示例4: __init__
# 需要导入模块: import weakref [as 别名]
# 或者: from weakref import ReferenceType [as 别名]
def __init__(
self,
tb: Union[TracebackType, Iterable[TracebackEntry]],
excinfo: Optional["ReferenceType[ExceptionInfo]"] = None,
) -> None:
""" initialize from given python traceback object and ExceptionInfo """
self._excinfo = excinfo
if isinstance(tb, TracebackType):
def f(cur: TracebackType) -> Iterable[TracebackEntry]:
cur_ = cur # type: Optional[TracebackType]
while cur_ is not None:
yield TracebackEntry(cur_, excinfo=excinfo)
cur_ = cur_.tb_next
super().__init__(f(tb))
else:
super().__init__(tb)
示例5: list_pubs
# 需要导入模块: import weakref [as 别名]
# 或者: from weakref import ReferenceType [as 别名]
def list_pubs():
# import pdb; pdb.set_trace()
import weakref
msg = []
for receiver in signals.post_save.receivers:
(receiver_class_name,_), receiver = receiver
# django.contrib.contenttypes.generic.GenericForeignKey.instance_pre_init is not weakref
if isinstance(receiver, weakref.ReferenceType):
receiver = receiver()
receiver = getattr(receiver, '__wraps__', receiver)
receiver_name = getattr(receiver, '__name__', str(receiver))
text = "%s.%s" % (receiver_class_name, receiver_name)
if receiver_name == 'publish_rdf' :
msg.append(text)
return str(msg)
示例6: emit
# 需要导入模块: import weakref [as 别名]
# 或者: from weakref import ReferenceType [as 别名]
def emit(self, *args):
# allow remove receiver during emitting
for receiver in self.receivers.copy():
try:
if self._is_alive(receiver):
if isinstance(receiver, weakref.ReferenceType):
func = receiver()
else:
func = receiver
if Signal.has_aio_support:
uid = gen_id(func)
aioqueue = uid in self.aioqueued_receiver_ids
if aioqueue:
Signal.aioqueue.sync_q.put_nowait((func, args))
else:
func(*args)
else:
func(*args)
else:
logger.debug('receiver:{} is dead'.format(receiver))
except Exception:
logger.exception('receiver %s raise error' % receiver)
示例7: __init__
# 需要导入模块: import weakref [as 别名]
# 或者: from weakref import ReferenceType [as 别名]
def __init__(self, imagecrawler: BaseImageCrawler, *,
weight: _CrawlerWeight = 1.0,
restart_at_front_when_exhausted: bool = False,
is_image_addable: Optional[_IsImageAddable] = None,
on_image_added: Optional[_OnImageAdded] = None
) -> None: # pragma: no cover
if weight <= 0:
raise ValueError('weight <= 0')
self.imagecrawler = imagecrawler
self.weight = weight
self.restart_at_front_when_exhausted = restart_at_front_when_exhausted
self.images = ImageCollection()
self._is_image_addable_wr: Optional[ReferenceType[_IsImageAddable]] = None
self._image_added_wr: Optional[ReferenceType[_OnImageAdded]] = None
self.set_is_image_addable(is_image_addable)
self.set_image_added(on_image_added)
示例8: __init__
# 需要导入模块: import weakref [as 别名]
# 或者: from weakref import ReferenceType [as 别名]
def __init__(
self,
key_processor_ref: "weakref.ReferenceType[KeyProcessor]",
arg: Optional[str],
key_sequence: List[KeyPress],
previous_key_sequence: List[KeyPress],
is_repeat: bool,
) -> None:
self._key_processor_ref = key_processor_ref
self.key_sequence = key_sequence
self.previous_key_sequence = previous_key_sequence
#: True when the previous key sequence was handled by the same handler.
self.is_repeat = is_repeat
self._arg = arg
self._app = get_app()
示例9: __init__
# 需要导入模块: import weakref [as 别名]
# 或者: from weakref import ReferenceType [as 别名]
def __init__(self, name: str, name_full: str,
sessionplayer: ba.SessionPlayer, stats: ba.Stats):
self.name = name
self.name_full = name_full
self.score = 0
self.accumscore = 0
self.kill_count = 0
self.accum_kill_count = 0
self.killed_count = 0
self.accum_killed_count = 0
self._multi_kill_timer: Optional[ba.Timer] = None
self._multi_kill_count = 0
self._stats = weakref.ref(stats)
self._last_sessionplayer: Optional[ba.SessionPlayer] = None
self._sessionplayer: Optional[ba.SessionPlayer] = None
self._sessionteam: Optional[ReferenceType[ba.SessionTeam]] = None
self.streak = 0
self.associate_with_sessionplayer(sessionplayer)
示例10: _verify_object_death
# 需要导入模块: import weakref [as 别名]
# 或者: from weakref import ReferenceType [as 别名]
def _verify_object_death(wref: ReferenceType) -> None:
obj = wref()
if obj is None:
return
try:
name = type(obj).__name__
except Exception:
print(f'Note: unable to get type name for {obj}')
name = 'object'
print(f'{Clr.RED}Error: {name} not dying'
f' when expected to: {Clr.BLD}{obj}{Clr.RST}')
refs = list(gc.get_referrers(obj))
print(f'{Clr.YLW}Active References:{Clr.RST}')
i = 1
for ref in refs:
print(f'{Clr.YLW} reference {i}:{Clr.BLU} {ref}{Clr.RST}')
i += 1
示例11: __init__
# 需要导入模块: import weakref [as 别名]
# 或者: from weakref import ReferenceType [as 别名]
def __init__(self) -> None:
size = config.val.tabs.focus_stack_size
if size < 0:
size = None
self._stack = collections.deque(
maxlen=size
) # type: typing.Deque[weakref.ReferenceType[QWidget]]
# Items that have been removed from the primary stack.
self._stack_deleted = [
] # type: typing.List[weakref.ReferenceType[QWidget]]
self._ignore_next = False
self._keep_deleted_next = False
示例12: _clear_dead_receivers
# 需要导入模块: import weakref [as 别名]
# 或者: from weakref import ReferenceType [as 别名]
def _clear_dead_receivers(self):
# Note: caller is assumed to hold self.lock.
if self._dead_receivers:
self._dead_receivers = False
new_receivers = []
for r in self.receivers:
if isinstance(r[1], weakref.ReferenceType) and r[1]() is None:
continue
new_receivers.append(r)
self.receivers = new_receivers
示例13: _live_receivers
# 需要导入模块: import weakref [as 别名]
# 或者: from weakref import ReferenceType [as 别名]
def _live_receivers(self, sender):
"""
Filter sequence of receivers to get resolved, live receivers.
This checks for weak references and resolves them, then returning only
live receivers.
"""
receivers = None
if self.use_caching and not self._dead_receivers:
receivers = self.sender_receivers_cache.get(sender)
# We could end up here with NO_RECEIVERS even if we do check this case in
# .send() prior to calling _live_receivers() due to concurrent .send() call.
if receivers is NO_RECEIVERS:
return []
if receivers is None:
with self.lock:
self._clear_dead_receivers()
senderkey = _make_id(sender)
receivers = []
for (receiverkey, r_senderkey), receiver in self.receivers:
if r_senderkey == NONE_ID or r_senderkey == senderkey:
receivers.append(receiver)
if self.use_caching:
if not receivers:
self.sender_receivers_cache[sender] = NO_RECEIVERS
else:
# Note, we must cache the weakref versions.
self.sender_receivers_cache[sender] = receivers
non_weak_receivers = []
for receiver in receivers:
if isinstance(receiver, weakref.ReferenceType):
# Dereference the weak reference.
receiver = receiver()
if receiver is not None:
non_weak_receivers.append(receiver)
else:
non_weak_receivers.append(receiver)
return non_weak_receivers
示例14: to_fmt
# 需要导入模块: import weakref [as 别名]
# 或者: from weakref import ReferenceType [as 别名]
def to_fmt(self) -> fmt.indentable:
res = None
showlist = {
'attr': {
"res": fmt.sep('', ['.']),
"inblock": fmt.sep('=', [self.value])
},
'indice': {
"res": fmt.block('[', ']', []),
"inblock": fmt.sep(': ', [repr(self.value)])
},
'key': {
"res": fmt.block('{', '}', []),
"inblock": fmt.sep(': ', [repr(self.value)])
}
}
for k in sorted(showlist.keys()):
v = showlist[k]
if self.kind == CaptureContext.kind_of_node[k]:
res = v["res"]
inblock = v["inblock"]
if self.node is not None:
if hasattr(self.node, 'to_fmt'):
inblock.lsdata.append(self.node.to_fmt())
elif type(self.node) is weakref.ReferenceType:
inblock.lsdata.append(repr(self.get()))
res.lsdata.append(inblock)
######
if self.kind == CaptureContext.kind_of_node['node']:
res = fmt.sep('', [self.value])
elmts = fmt.sep(',\n', [])
for sk in sorted(CaptureContext.map_intern.values()):
subelmt = None
if hasattr(self, sk):
subelmt = getattr(self, sk)
if subelmt is not None:
for sube in subelmt:
elmts.lsdata.append(sube.to_fmt())
se = fmt.tab(fmt.block('(\n', '\n)', elmts))
res.lsdata.append(se)
return res
示例15: test_alive
# 需要导入模块: import weakref [as 别名]
# 或者: from weakref import ReferenceType [as 别名]
def test_alive(self):
o = Object(1)
r = weakref.WeakMethod(o.some_method)
self.assertIsInstance(r, weakref.ReferenceType)
self.assertIsInstance(r(), type(o.some_method))
self.assertIs(r().__self__, o)
self.assertIs(r().__func__, o.some_method.__func__)
self.assertEqual(r()(), 4)