本文整理匯總了Python中inspect.isframe方法的典型用法代碼示例。如果您正苦於以下問題:Python inspect.isframe方法的具體用法?Python inspect.isframe怎麽用?Python inspect.isframe使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類inspect
的用法示例。
在下文中一共展示了inspect.isframe方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _format
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isframe [as 別名]
def _format(self, obj, descend=True):
"""Return a string representation of a single object."""
if inspect.isframe(obj):
filename, lineno, func, context, index = inspect.getframeinfo(obj)
return "<frame of function '%s'>" % func
if not descend:
return self.peek(repr(obj))
if isinstance(obj, dict):
return '{' + ', '.join(['%s: %s' % (self._format(k, descend=False),
self._format(v, descend=False))
for k, v in obj.items()]) + '}'
elif isinstance(obj, list):
return '[' + ', '.join([self._format(item, descend=False)
for item in obj]) + ']'
elif isinstance(obj, tuple):
return '(' + ', '.join([self._format(item, descend=False)
for item in obj]) + ')'
r = self.peek(repr(obj))
if isinstance(obj, (str, int, float)):
return r
return '%s: %s' % (type(obj), r)
示例2: _getfile
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isframe [as 別名]
def _getfile(object):
"""
Override inspect.getfile
A common idiom within Obspy to get a file path of the current code
(eg. to find a data file in the same package) is
>>> inspect.getfile(inspect.currentframe())
This doesn't work in PyInstaller for some reason.
In every case I've tried, this returns the same thing as __file__,
which does work in PyInstaller, so this hook tries to return that instead.
"""
if inspect.isframe(object):
try:
file = object.f_globals['__file__']
# print("inspect.getfile returning %s" % file)
return file
except:
pass
return _old_getfile(object)
示例3: test_excluding_predicates
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isframe [as 別名]
def test_excluding_predicates(self):
self.istest(inspect.isbuiltin, 'sys.exit')
self.istest(inspect.isbuiltin, '[].append')
self.istest(inspect.iscode, 'mod.spam.func_code')
self.istest(inspect.isframe, 'tb.tb_frame')
self.istest(inspect.isfunction, 'mod.spam')
self.istest(inspect.ismethod, 'mod.StupidGit.abuse')
self.istest(inspect.ismethod, 'git.argue')
self.istest(inspect.ismodule, 'mod')
self.istest(inspect.istraceback, 'tb')
self.istest(inspect.isdatadescriptor, '__builtin__.file.closed')
self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace')
self.istest(inspect.isgenerator, '(x for x in xrange(2))')
self.istest(inspect.isgeneratorfunction, 'generator_function_example')
if hasattr(types, 'GetSetDescriptorType'):
self.istest(inspect.isgetsetdescriptor,
'type(tb.tb_frame).f_locals')
else:
self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
if hasattr(types, 'MemberDescriptorType'):
self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days')
else:
self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days))
示例4: _format
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isframe [as 別名]
def _format(self, obj, descend=True):
"""Return a string representation of a single object."""
if inspect.isframe(obj):
filename, lineno, func, context, index = inspect.getframeinfo(obj)
return "<frame of function '%s'>" % func
if not descend:
return self.peek(repr(obj))
if isinstance(obj, dict):
return "{" + ", ".join(["%s: %s" % (self._format(k, descend=False),
self._format(v, descend=False))
for k, v in obj.items()]) + "}"
elif isinstance(obj, list):
return "[" + ", ".join([self._format(item, descend=False)
for item in obj]) + "]"
elif isinstance(obj, tuple):
return "(" + ", ".join([self._format(item, descend=False)
for item in obj]) + ")"
r = self.peek(repr(obj))
if isinstance(obj, (str, int, float)):
return r
return "%s: %s" % (type(obj), r)
示例5: code
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isframe [as 別名]
def code(func):
'''get the code object for the given function or method
NOTE: use dill.source.getsource(CODEOBJ) to get the source code
'''
if PY3:
im_func = '__func__'
func_code = '__code__'
else:
im_func = 'im_func'
func_code = 'func_code'
if ismethod(func): func = getattr(func, im_func)
if isfunction(func): func = getattr(func, func_code)
if istraceback(func): func = func.tb_frame
if isframe(func): func = func.f_code
if iscode(func): return func
return
#XXX: ugly: parse dis.dis for name after "<code object" in line and in globals?
示例6: _isinstance
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isframe [as 別名]
def _isinstance(object):
'''True if object is a class instance type (and is not a builtin)'''
if _hascode(object) or isclass(object) or ismodule(object):
return False
if istraceback(object) or isframe(object) or iscode(object):
return False
# special handling (numpy arrays, ...)
if not getmodule(object) and getmodule(type(object)).__name__ in ['numpy']:
return True
# # check if is instance of a builtin
# if not getmodule(object) and getmodule(type(object)).__name__ in ['__builtin__','builtins']:
# return False
_types = ('<class ',"<type 'instance'>")
if not repr(type(object)).startswith(_types): #FIXME: weak hack
return False
if not getmodule(object) or object.__module__ in ['builtins','__builtin__'] or getname(object, force=True) in ['array']:
return False
return True # by process of elimination... it's what we want
示例7: test_methods_garbage_collection
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isframe [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))
示例8: test_excluding_predicates
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isframe [as 別名]
def test_excluding_predicates(self):
#self.istest(inspect.isbuiltin, 'sys.exit') # Not valid for Jython
self.istest(inspect.isbuiltin, '[].append')
self.istest(inspect.iscode, 'mod.spam.func_code')
self.istest(inspect.isframe, 'tb.tb_frame')
self.istest(inspect.isfunction, 'mod.spam')
self.istest(inspect.ismethod, 'mod.StupidGit.abuse')
self.istest(inspect.ismethod, 'git.argue')
self.istest(inspect.ismodule, 'mod')
self.istest(inspect.istraceback, 'tb')
self.istest(inspect.isdatadescriptor, '__builtin__.file.closed')
self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace')
self.istest(inspect.isgenerator, '(x for x in xrange(2))')
self.istest(inspect.isgeneratorfunction, 'generator_function_example')
if hasattr(types, 'GetSetDescriptorType'):
self.istest(inspect.isgetsetdescriptor,
'type(tb.tb_frame).f_locals')
else:
self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
if hasattr(types, 'MemberDescriptorType'):
# Not valid for Jython
# self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days')
pass
else:
self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days))
示例9: ascend
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isframe [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
示例10: isdata
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isframe [as 別名]
def isdata(object):
"""Check if an object is of a type that probably means it's data."""
return not (inspect.ismodule(object) or inspect.isclass(object) or
inspect.isroutine(object) or inspect.isframe(object) or
inspect.istraceback(object) or inspect.iscode(object))
示例11: from_built_in_frame
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isframe [as 別名]
def from_built_in_frame(cls, frame):
"""Create a new instance from built-in frame object."""
assert inspect.isframe(frame), 'Expect FrameType; Got %s' % type(frame)
return cls(
file=os.path.abspath(frame.f_code.co_filename),
line=int(frame.f_lineno),
)
示例12: getArgValues
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isframe [as 別名]
def getArgValues(frame):
"""Provides information about arguments passed into a particular frame"""
if not isframe(frame):
raise TypeError('{0!r} is not a frame object'.format(frame))
args, varargs, kwonlyargs, varkw = _getfullargs(frame.f_code)
return ArgInfo(args + kwonlyargs, varargs, varkw, frame.f_locals)
示例13: _process_in_memory_objects
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isframe [as 別名]
def _process_in_memory_objects(objects):
"""Processes objects tracked by GC.
Processing is done in separate function to avoid generating overhead.
"""
return _remove_duplicates(obj for obj in objects
if not inspect.isframe(obj))
示例14: test_abuse_done
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isframe [as 別名]
def test_abuse_done(self):
self.istest(inspect.istraceback, 'git.ex[2]')
self.istest(inspect.isframe, 'mod.fr')
示例15: list_referrers
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isframe [as 別名]
def list_referrers(self, exclude=[], depth=0):
"""List all the referrers of the tracked objects.
Can exlude some objects and go to deeper levels (referrers of the
referrers) in which case reference to the first object are filtered.
References held by frames are also filtered
This function is mostly useful when tracking why an object that is
expected to be released is not.
"""
gc.collect()
def find_referrers(ref_dict, obj, depth=0, exclude=[]):
"""Find the object referring the specified object.
"""
referrers = [ref for ref in gc.get_referrers(obj)
if not (inspect.isframe(ref) or
ref in exclude)]
if depth == 0:
ref_dict[obj] = referrers
else:
deeper = {}
for r in referrers:
find_referrers(deeper, r, depth-1,
exclude + [obj, referrers])
ref_dict[obj] = deeper
tracked = {}
objs = [r for r in self._refs if r not in exclude]
for r in objs:
find_referrers(tracked, r, depth, [objs])
return tracked