def introspect_docstring_lineno(api_doc):
"""
Try to determine the line number on which the given item's
docstring begins. Return the line number, or C{None} if the line
number can't be determined. The line number of the first line in
the file is 1.
"""
if api_doc.docstring_lineno is not UNKNOWN:
return api_doc.docstring_lineno
if isinstance(api_doc, ValueDoc) and api_doc.pyval is not UNKNOWN:
try:
lines, lineno = inspect.findsource(api_doc.pyval)
if not isinstance(api_doc, ModuleDoc): lineno += 1
for lineno in range(lineno, len(lines)):
if lines[lineno].split('#', 1)[0].strip():
api_doc.docstring_lineno = lineno + 1
return lineno + 1
except IOError: pass
except TypeError: pass
except IndexError:
log.warning('inspect.findsource(%s) raised IndexError'
% api_doc.canonical_name)
return None
python类findsource()的实例源码
def _printlonglist(self, linerange=None):
try:
if self.curframe.f_code.co_name == '<module>':
# inspect.getsourcelines is buggy in this case: if we just
# pass the frame, it returns the source for the first function
# defined in the module. Instead, we want the full source
# code of the module
lines, _ = inspect.findsource(self.curframe)
lineno = 1
else:
try:
lines, lineno = inspect.getsourcelines(self.curframe)
except Exception as e:
print('** Error in inspect.getsourcelines: %s **' % e, file=self.stdout)
return
except IOError as e:
print('** Error: %s **' % e, file=self.stdout)
return
if linerange:
start, end = linerange
start = max(start, lineno)
end = min(end, lineno+len(lines))
lines = lines[start-lineno:end-lineno]
lineno = start
self._print_lines_pdbpp(lines, lineno)
def with_patch_inspect(f):
"""
Deprecated since IPython 6.0
decorator for monkeypatching inspect.findsource
"""
def wrapped(*args, **kwargs):
save_findsource = inspect.findsource
save_getargs = inspect.getargs
inspect.findsource = findsource
inspect.getargs = getargs
try:
return f(*args, **kwargs)
finally:
inspect.findsource = save_findsource
inspect.getargs = save_getargs
return wrapped
def _number_of_line(member):
"""Try to return the number of the first line of the definition of a
member of a module."""
if isinstance(member, tuple):
member = member[1]
try:
return member.__code__.co_firstlineno
except AttributeError:
pass
try:
return inspect.findsource(member)[1]
except BaseException:
pass
for (key, value) in vars(member).items():
try:
return value.__code__.co_firstlineno
except AttributeError:
pass
else:
return 0
def get_current_frame_data(self):
"""
Get all date about the current execution frame
:return: current frame data
:rtype: dict
:raises AttributeError: if the debugger does hold any execution frame.
:raises IOError: if source code for the current execution frame is not accessible.
"""
filename = self.curframe.f_code.co_filename
lines, start_line = inspect.findsource(self.curframe)
if sys.version_info[0] == 2:
lines = [line.decode('utf-8') for line in lines]
return {
'filename': os.path.basename(filename),
'listing': ''.join(lines),
'curr_line': self.curframe.f_lineno,
'total_lines': len(lines),
'breaklist': self.get_file_breaks(filename),
}
def GetFileAndLine(component):
"""Returns the filename and line number of component.
Args:
component: A component to find the source information for, usually a class
or routine.
Returns:
filename: The name of the file where component is defined.
lineno: The line number where component is defined.
"""
if inspect.isbuiltin(component):
return None, None
try:
filename = inspect.getsourcefile(component)
except TypeError:
return None, None
try:
unused_code, lineindex = inspect.findsource(component)
lineno = lineindex + 1
except IOError:
lineno = None
return filename, lineno
def test_getfslineno():
from py.code import getfslineno
def f(x):
pass
fspath, lineno = getfslineno(f)
assert fspath.basename == "test_source.py"
assert lineno == py.code.getrawcode(f).co_firstlineno-1 # see findsource
class A(object):
pass
fspath, lineno = getfslineno(A)
_, A_lineno = inspect.findsource(A)
assert fspath.basename == "test_source.py"
assert lineno == A_lineno
assert getfslineno(3) == ("", -1)
class B:
pass
B.__name__ = "B2"
assert getfslineno(B)[1] == -1
def with_patch_inspect(f):
"""
Deprecated since IPython 6.0
decorator for monkeypatching inspect.findsource
"""
def wrapped(*args, **kwargs):
save_findsource = inspect.findsource
save_getargs = inspect.getargs
inspect.findsource = findsource
inspect.getargs = getargs
try:
return f(*args, **kwargs)
finally:
inspect.findsource = save_findsource
inspect.getargs = save_getargs
return wrapped
def getsourcelines(self, obj):
lines, lineno = inspect.findsource(obj)
if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
# must be a module frame: do not try to cut a block out of it
return lines, 1
elif inspect.ismodule(obj):
return lines, 1
return inspect.getblock(lines[lineno:]), lineno+1
def getsourcelines(obj):
lines, lineno = inspect.findsource(obj)
if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
# must be a module frame: do not try to cut a block out of it
return lines, 1
elif inspect.ismodule(obj):
return lines, 1
return inspect.getblock(lines[lineno:]), lineno+1
def test_findsource_binary(self):
self.assertRaises(IOError, inspect.getsource, unicodedata)
self.assertRaises(IOError, inspect.findsource, unicodedata)
def test_findsource_code_in_linecache(self):
lines = ["x=1"]
co = compile(lines[0], "_dynamically_created_file", "exec")
self.assertRaises(IOError, inspect.findsource, co)
self.assertRaises(IOError, inspect.getsource, co)
linecache.cache[co.co_filename] = (1, None, lines, co.co_filename)
self.assertEqual(inspect.findsource(co), (lines,0))
self.assertEqual(inspect.getsource(co), lines[0])
def _class_get_line(clss):
return inspect.findsource(clss)[1]
def test_findsource_binary(self):
self.assertRaises(IOError, inspect.getsource, unicodedata)
self.assertRaises(IOError, inspect.findsource, unicodedata)
def test_findsource_code_in_linecache(self):
lines = ["x=1"]
co = compile(lines[0], "_dynamically_created_file", "exec")
self.assertRaises(IOError, inspect.findsource, co)
self.assertRaises(IOError, inspect.getsource, co)
linecache.cache[co.co_filename] = (1, None, lines, co.co_filename)
self.assertEqual(inspect.findsource(co), (lines,0))
self.assertEqual(inspect.getsource(co), lines[0])
def test_findsource_without_filename(self):
for fname in ['', '<string>']:
co = compile('x=1', fname, "exec")
self.assertRaises(IOError, inspect.findsource, co)
self.assertRaises(IOError, inspect.getsource, co)
def test_findsource_binary(self):
self.assertRaises(IOError, inspect.getsource, unicodedata)
self.assertRaises(IOError, inspect.findsource, unicodedata)
def test_findsource_code_in_linecache(self):
lines = ["x=1"]
co = compile(lines[0], "_dynamically_created_file", "exec")
self.assertRaises(IOError, inspect.findsource, co)
self.assertRaises(IOError, inspect.getsource, co)
linecache.cache[co.co_filename] = (1, None, lines, co.co_filename)
self.assertEqual(inspect.findsource(co), (lines,0))
self.assertEqual(inspect.getsource(co), lines[0])
def test_findsource_without_filename(self):
for fname in ['', '<string>']:
co = compile('x=1', fname, "exec")
self.assertRaises(IOError, inspect.findsource, co)
self.assertRaises(IOError, inspect.getsource, co)
def getsourcelines(obj):
lines, lineno = inspect.findsource(obj)
if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
# must be a module frame: do not try to cut a block out of it
return lines, 1
elif inspect.ismodule(obj):
return lines, 1
return inspect.getblock(lines[lineno:]), lineno+1
def test_findsource_binary(self):
self.assertRaises(IOError, inspect.getsource, unicodedata)
self.assertRaises(IOError, inspect.findsource, unicodedata)
def test_findsource_code_in_linecache(self):
lines = ["x=1"]
co = compile(lines[0], "_dynamically_created_file", "exec")
self.assertRaises(IOError, inspect.findsource, co)
self.assertRaises(IOError, inspect.getsource, co)
linecache.cache[co.co_filename] = (1, None, lines, co.co_filename)
try:
self.assertEqual(inspect.findsource(co), (lines,0))
self.assertEqual(inspect.getsource(co), lines[0])
finally:
del linecache.cache[co.co_filename]
def test_findsource_without_filename(self):
for fname in ['', '<string>']:
co = compile('x=1', fname, "exec")
self.assertRaises(IOError, inspect.findsource, co)
self.assertRaises(IOError, inspect.getsource, co)
def Info(component):
"""Returns a dict with information about the given component.
The dict will have at least some of the following fields.
type_name: The type of `component`.
string_form: A string representation of `component`.
file: The file in which `component` is defined.
line: The line number at which `component` is defined.
docstring: The docstring of `component`.
init_docstring: The init docstring of `component`.
class_docstring: The class docstring of `component`.
call_docstring: The call docstring of `component`.
length: The length of `component`.
Args:
component: The component to analyze.
Returns:
A dict with information about the component.
"""
try:
from IPython.core import oinspect # pylint: disable=g-import-not-at-top
inspector = oinspect.Inspector()
info = inspector.info(component)
except ImportError:
info = _InfoBackup(component)
try:
unused_code, lineindex = inspect.findsource(component)
info['line'] = lineindex + 1
except (TypeError, IOError):
info['line'] = None
return info
def with_patch_inspect(f):
"""decorator for monkeypatching inspect.findsource"""
def wrapped(*args, **kwargs):
save_findsource = inspect.findsource
save_getargs = inspect.getargs
inspect.findsource = findsource
inspect.getargs = getargs
try:
return f(*args, **kwargs)
finally:
inspect.findsource = save_findsource
inspect.getargs = save_getargs
return wrapped
def getsourcelines(self, obj):
lines, lineno = inspect.findsource(obj)
if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
# must be a module frame: do not try to cut a block out of it
return lines, 1
elif inspect.ismodule(obj):
return lines, 1
return inspect.getblock(lines[lineno:]), lineno+1
def test_findsource_binary(self):
self.assertRaises(IOError, inspect.getsource, unicodedata)
self.assertRaises(IOError, inspect.findsource, unicodedata)
def test_findsource_code_in_linecache(self):
lines = ["x=1"]
co = compile(lines[0], "_dynamically_created_file", "exec")
self.assertRaises(IOError, inspect.findsource, co)
self.assertRaises(IOError, inspect.getsource, co)
linecache.cache[co.co_filename] = (1, None, lines, co.co_filename)
self.assertEqual(inspect.findsource(co), (lines,0))
self.assertEqual(inspect.getsource(co), lines[0])
def test_findsource_without_filename(self):
for fname in ['', '<string>']:
co = compile('x=1', fname, "exec")
self.assertRaises(IOError, inspect.findsource, co)
self.assertRaises(IOError, inspect.getsource, co)
def getsourcelines(obj):
lines, lineno = inspect.findsource(obj)
if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
# must be a module frame: do not try to cut a block out of it
return lines, 1
elif inspect.ismodule(obj):
return lines, 1
return inspect.getblock(lines[lineno:]), lineno+1