本文整理汇总了Python中gc.get_referrers方法的典型用法代码示例。如果您正苦于以下问题:Python gc.get_referrers方法的具体用法?Python gc.get_referrers怎么用?Python gc.get_referrers使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类gc
的用法示例。
在下文中一共展示了gc.get_referrers方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: step
# 需要导入模块: import gc [as 别名]
# 或者: from gc import get_referrers [as 别名]
def step(self):
bgan = self.gan
self.gan.step()
if bgan.destroy:
self.sampler=None
self.gan = self.gan.newgan
gc.collect()
refs = gc.get_referrers(bgan)
d = bgan.trainer._delegate
bgan.trainer=None
gc.collect()
del bgan
tf.reset_default_graph()
gc.collect()
if(self.steps % self.sample_every == 0):
sample_list = self.sample()
self.steps+=1
示例2: find_backref_chain
# 需要导入模块: import gc [as 别名]
# 或者: from gc import get_referrers [as 别名]
def find_backref_chain(obj, predicate, max_depth=20, extra_ignore=()):
"""Find a shortest chain of references leading to obj.
The start of the chain will be some object that matches your predicate.
``predicate`` is a function taking one argument and returning a boolean.
``max_depth`` limits the search depth.
``extra_ignore`` can be a list of object IDs to exclude those objects from
your search.
Example:
>>> find_backref_chain(obj, inspect.ismodule)
[<module ...>, ..., obj]
Returns ``[obj]`` if such a chain could not be found.
.. versionchanged:: 1.5
Returns ``obj`` instead of ``None`` when a chain could not be found.
"""
return find_chain(obj, predicate, gc.get_referrers,
max_depth=max_depth, extra_ignore=extra_ignore)
示例3: test_it
# 需要导入模块: import gc [as 别名]
# 或者: from gc import get_referrers [as 别名]
def test_it(collectible):
dd()
dd('======= ', ('collectible' if collectible else 'uncollectible'), ' object =======')
dd()
gc.collect()
dd('*** init, nr of referrers: ', len(gc.get_referrers(One)))
dd(' garbage: ', gc.garbage)
one = One(collectible)
dd(' created: ', one.typ, ': ', one)
dd(' nr of referrers: ', len(gc.get_referrers(One)))
dd(' delete:')
del one
gc.collect()
dd('*** after gc, nr of referrers: ', len(gc.get_referrers(One)))
dd(' garbage: ', gc.garbage)
示例4: print_referrers
# 需要导入模块: import gc [as 别名]
# 或者: from gc import get_referrers [as 别名]
def print_referrers(obj, dbg=False):
import gc
for referrer in gc.get_referrers(obj):
if isinstance(referrer, dict):
for field, value in referrer.items():
if value is obj:
print referrer, field
elif hasattr(referrer, '__dict__'):
for field,value in referrer.__dict__.items():
if value is obj:
print referrer, field
elif hasattr(referrer, 'remove'):
print referrer
elif type(referrer) == tuple:
clear_referrers(referrer, dbg=True)
else:
#import pprint
#pp = pprint.PrettyPrinter(indent=4)
#pp.pprint(referrer)
pass
示例5: disable_splitbrain
# 需要导入模块: import gc [as 别名]
# 或者: from gc import get_referrers [as 别名]
def disable_splitbrain():
"""Disables (deactivates) the Splitbrain machinery"""
global _enabled
if not _enabled:
return
_enabled = False
for funcname, origfunc in _prev_builtins.items():
setattr(builtins, funcname, origfunc)
for modname, mod in sys.modules.items():
if isinstance(mod, RoutedModule):
sys.modules[modname] = mod.__realmod__
for ref in gc.get_referrers(mod):
if isinstance(ref, dict) and "__name__" in ref and ref.get("__file__") is not None:
for k, v in ref.items():
if v is mod:
ref[k] = mod.__realmod__
sys.modules["sys"] = sys
builtins.__import__ = _orig_import
示例6: obj_referrers
# 需要导入模块: import gc [as 别名]
# 或者: from gc import get_referrers [as 别名]
def obj_referrers(klass):
find_obj = False
for obj in gc.get_objects():
# closures are evil !
if isinstance(obj, types.FunctionType) and obj.__closure__ is not None:
for c in obj.__closure__:
try:
if isinstance(c.cell_contents, klass):
print('!!!', obj, c.cell_contents)
except ValueError:
print("Cell is empty...")
if isinstance(obj, klass):
find_obj = True
rs = gc.get_referrers(obj)
print("---------------------------referrers of %s" % klass.__name__)
for ob in rs:
print(type(ob), ob.__name__ if type(ob) is type else repr(ob)[:140])
rs1 = gc.get_referrers(ob)
for ob1 in rs1:
print(' ', type(ob1), ob1.__name__ if type(ob1) is type else repr(ob1)[:140])
print("---------------------------")
if not find_obj:
print("Nothing refrences %s" % klass.__name__)
示例7: load
# 需要导入模块: import gc [as 别名]
# 或者: from gc import get_referrers [as 别名]
def load(self):
import iris
imp.reload(iris)
imp.reload(iris.config)
config = iris.config.load_config(sys.argv[1])
import iris.api
app = iris.api.get_api(config)
if not self.skip_build_assets:
for r in gc.get_referrers(self):
if isinstance(r, dict) and '_num_workers' in r:
gunicorn_arbiter = r
# only build assets on one worker to avoid race conditions
if gunicorn_arbiter['worker_age'] % self.options['workers'] == 0:
import iris.ui
iris.ui.build_assets()
return app
示例8: load
# 需要导入模块: import gc [as 别名]
# 或者: from gc import get_referrers [as 别名]
def load(self):
import oncall
importlib.reload(oncall.utils)
import oncall.app
app = oncall.app.get_wsgi_app()
if not self.skip_build_assets:
for r in gc.get_referrers(self):
if isinstance(r, dict) and '_num_workers' in r:
gunicorn_arbiter = r
# only build assets on one worker to avoid race conditions
if gunicorn_arbiter['worker_age'] % self.options['workers'] == 0:
import oncall.ui
oncall.ui.build_assets()
return app
示例9: _verify_object_death
# 需要导入模块: import gc [as 别名]
# 或者: from gc import get_referrers [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
示例10: test_methods_garbage_collection
# 需要导入模块: import gc [as 别名]
# 或者: from gc import get_referrers [as 别名]
def test_methods_garbage_collection(self):
class Randomy(object):
@memoize
def randomy(self, do_random):
if do_random:
return random.random()
else:
return "constant"
r = Randomy()
rand1 = r.randomy(True)
for gc_ref in gc.get_referrers(r):
if inspect.isframe(gc_ref):
continue
else:
raise AssertionError('Unexpected reference to `r` instance: {!r}\n'
'@memoize probably made a reference to it and has created a circular reference loop'.format(gc_ref))
示例11: ascend
# 需要导入模块: import gc [as 别名]
# 或者: from gc import get_referrers [as 别名]
def ascend(self, obj, depth=1):
"""Return a nested list containing referrers of the given object."""
depth += 1
parents = []
# Gather all referrers in one step to minimize
# cascading references due to repr() logic.
refs = gc.get_referrers(obj)
self.ignore.append(refs)
if len(refs) > self.maxparents:
return [('[%s referrers]' % len(refs), [])]
try:
ascendcode = self.ascend.__code__
except AttributeError:
ascendcode = self.ascend.im_func.func_code
for parent in refs:
if inspect.isframe(parent) and parent.f_code is ascendcode:
continue
if parent in self.ignore:
continue
if depth <= self.maxdepth:
parents.append((parent, self.ascend(parent, depth)))
else:
parents.append((parent, []))
return parents
示例12: show_backrefs
# 需要导入模块: import gc [as 别名]
# 或者: from gc import get_referrers [as 别名]
def show_backrefs(objs, max_depth=3, extra_ignore=(), filter=None, too_many=10,
highlight=None):
"""Generate an object reference graph ending at ``objs``
The graph will show you what objects refer to ``objs``, directly and
indirectly.
``objs`` can be a single object, or it can be a list of objects.
Produces a Graphviz .dot file and spawns a viewer (xdot) if one is
installed, otherwise converts the graph to a .png image.
Use ``max_depth`` and ``too_many`` to limit the depth and breadth of the
graph.
Use ``filter`` (a predicate) and ``extra_ignore`` (a list of object IDs) to
remove undesired objects from the graph.
Use ``highlight`` (a predicate) to highlight certain graph nodes in blue.
Examples:
>>> show_backrefs(obj)
>>> show_backrefs([obj1, obj2])
>>> show_backrefs(obj, max_depth=5)
>>> show_backrefs(obj, filter=lambda x: not inspect.isclass(x))
>>> show_backrefs(obj, highlight=inspect.isclass)
>>> show_backrefs(obj, extra_ignore=[id(locals())])
"""
show_graph(objs, max_depth=max_depth, extra_ignore=extra_ignore,
filter=filter, too_many=too_many, highlight=highlight,
edge_func=gc.get_referrers, swap_source_target=False)
示例13: printReferences
# 需要导入模块: import gc [as 别名]
# 或者: from gc import get_referrers [as 别名]
def printReferences(obj):
"""Prints the object references"""
if obj is None:
print('No object to print references')
else:
refs = gc.get_referrers(obj)
print('Object references (total ' + str(len(refs)) + '):')
for item in refs:
print('---')
print(type(item))
val = repr(item)
if len(val) > 512:
print('Truncated: ' + val[:512])
else:
print(val)
示例14: describeObj
# 需要导入模块: import gc [as 别名]
# 或者: from gc import get_referrers [as 别名]
def describeObj(obj, depth=4, path=None, ignore=None):
"""
Trace all reference paths backward, printing a list of different ways this object can be accessed.
Attempts to answer the question "who has a reference to this object"
"""
if path is None:
path = [obj]
if ignore is None:
ignore = {} ## holds IDs of objects used within the function.
ignore[id(sys._getframe())] = None
ignore[id(path)] = None
gc.collect()
refs = gc.get_referrers(obj)
ignore[id(refs)] = None
printed=False
for ref in refs:
if id(ref) in ignore:
continue
if id(ref) in list(map(id, path)):
print("Cyclic reference: " + refPathString([ref]+path))
printed = True
continue
newPath = [ref]+path
if len(newPath) >= depth:
refStr = refPathString(newPath)
if '[_]' not in refStr: ## ignore '_' references generated by the interactive shell
print(refStr)
printed = True
else:
describeObj(ref, depth, newPath, ignore)
printed = True
if not printed:
print("Dead end: " + refPathString(path))
示例15: file_module_function_of
# 需要导入模块: import gc [as 别名]
# 或者: from gc import get_referrers [as 别名]
def file_module_function_of(self, frame):
code = frame.f_code
filename = code.co_filename
if filename:
modulename = modname(filename)
else:
modulename = None
funcname = code.co_name
clsname = None
if code in self._caller_cache:
if self._caller_cache[code] is not None:
clsname = self._caller_cache[code]
else:
self._caller_cache[code] = None
## use of gc.get_referrers() was suggested by Michael Hudson
# all functions which refer to this code object
funcs = [f for f in gc.get_referrers(code)
if inspect.isfunction(f)]
# require len(func) == 1 to avoid ambiguity caused by calls to
# new.function(): "In the face of ambiguity, refuse the
# temptation to guess."
if len(funcs) == 1:
dicts = [d for d in gc.get_referrers(funcs[0])
if isinstance(d, dict)]
if len(dicts) == 1:
classes = [c for c in gc.get_referrers(dicts[0])
if hasattr(c, "__bases__")]
if len(classes) == 1:
# ditto for new.classobj()
clsname = classes[0].__name__
# cache the result - assumption is that new.* is
# not called later to disturb this relationship
# _caller_cache could be flushed if functions in
# the new module get called.
self._caller_cache[code] = clsname
if clsname is not None:
funcname = "%s.%s" % (clsname, funcname)
return filename, modulename, funcname