Python inspect.findsource() Examples
The following are 30
code examples of inspect.findsource().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
inspect
, or try the search function
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: test_source.py From pytest with MIT License | 6 votes |
def test_findsource(monkeypatch) -> None: from _pytest._code.source import findsource filename = "<pytest-test_findsource>" lines = ["if 1:\n", " def x():\n", " pass\n"] co = compile("".join(lines), filename, "exec") # Type ignored because linecache.cache is private. monkeypatch.setitem(linecache.cache, filename, (1, None, lines, filename)) # type: ignore[attr-defined] src, lineno = findsource(co) assert src is not None assert "if 1:" in str(src) d = {} # type: Dict[str, Any] eval(co, d) src, lineno = findsource(d["x"]) assert src is not None assert "if 1:" in str(src) assert src[lineno] == " def x():"
Example #2
Source File: conf.py From python-sdc-client with MIT License | 6 votes |
def linkcode_resolve(domain, info): def find_line(): obj = sys.modules[info['module']] for part in info['fullname'].split('.'): obj = getattr(obj, part) import inspect fn = inspect.getsourcefile(obj) source, lineno = inspect.findsource(obj) return lineno + 1 if domain != 'py' or not info['module']: return None #tag = 'master' if 'dev' in release else ('v' + release) url = "https://github.com/draios/python-sdc-client/blob/master/sdcclient/_client.py" try: return url + '#L%d' % find_line() except Exception: return url
Example #3
Source File: __init__.py From python-web-pdb with MIT License | 6 votes |
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 { 'dirname': os.path.dirname(os.path.abspath(filename)) + os.path.sep, 'filename': os.path.basename(filename), 'file_listing': ''.join(lines), 'current_line': self.curframe.f_lineno, 'breakpoints': self.get_file_breaks(filename), 'globals': self.get_globals(), 'locals': self.get_locals() }
Example #4
Source File: conf.py From pyx with GNU General Public License v2.0 | 6 votes |
def unprocessed_function_signature(app, what, name, obj, options, sig, retann): # extract the unprocessed signature from the source if what not in ["class", "method", "staticmethod", "function"]: return if what == "class": # get the constructor (code copied from autodoc) obj = getattr(obj, "__init__", None) if obj is None or obj is object.__init__ or not \ (inspect.ismethod(obj) or inspect.isfunction(obj)): return elif hasattr(obj, '__wrapped__'): obj = obj.__wrapped__ src, line = inspect.findsource(obj) code = " ".join(function_signature_lines(src[line:])).split("(", 1)[1][:-2] if code.startswith("self, "): code = code[6:] elif code == "self": code = "" return "({})".format(code), retann
Example #5
Source File: test_source.py From py with MIT License | 6 votes |
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
Example #6
Source File: autodoctools.py From hydpy with GNU Lesser General Public License v3.0 | 6 votes |
def _number_of_line(member_tuple): """Try to return the number of the first line of the definition of a member of a module.""" member = member_tuple[1] try: return member.__code__.co_firstlineno except AttributeError: pass try: return inspect.findsource(member)[1] except BaseException: pass for value in vars(member).values(): try: return value.__code__.co_firstlineno except AttributeError: pass return 0
Example #7
Source File: _js.py From flexx with BSD 2-Clause "Simplified" License | 5 votes |
def __init__(self, cls=None): filename = None linenr = 1e9 if cls is not None: filename = getattr(sys.modules[cls.__module__], '__file__', None) if hasattr(cls, '__linenr__'): linenr = cls.__linenr__ else: try: linenr = inspect.findsource(cls)[1] except Exception: # e.g. in the notebook pass self.meta = {'vars_unknown': set(), 'vars_global': set(), 'std_functions': set(), 'std_methods': set(), 'filename': filename, 'linenr': linenr}
Example #8
Source File: test_inspect.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
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)
Example #9
Source File: stubfile_2_converter.py From pytypes with Apache License 2.0 | 5 votes |
def _class_get_line(clss): return inspect.findsource(clss)[1]
Example #10
Source File: test_inspect.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_findsource_binary(self): self.assertRaises(IOError, inspect.getsource, unicodedata) self.assertRaises(IOError, inspect.findsource, unicodedata)
Example #11
Source File: test_inspect.py From CTFCrackTools-V2 with GNU General Public License v3.0 | 5 votes |
def test_findsource_binary(self): self.assertRaises(IOError, inspect.getsource, unicodedata) self.assertRaises(IOError, inspect.findsource, unicodedata)
Example #12
Source File: test_inspect.py From CTFCrackTools-V2 with GNU General Public License v3.0 | 5 votes |
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])
Example #13
Source File: test_definition_order.py From wemake-python-styleguide with MIT License | 5 votes |
def _get_sorted_classes(classes): sorted_by_code = sorted(classes, key=lambda cl: cl.code) sorted_by_source = sorted( classes, key=lambda cl: inspect.findsource(cl)[1], ) return sorted_by_code, sorted_by_source
Example #14
Source File: myinspect.py From ver-observer with GNU General Public License v3.0 | 5 votes |
def getsourcelines(obj): obj = _unwrap(obj) lines, lnum = inspect.findsource(obj) if inspect.ismodule(obj): return lines, 0 else: return getblock(lines[lnum:]), lnum + 1
Example #15
Source File: test_inspect.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
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])
Example #16
Source File: pdb.py From android_universal with MIT License | 5 votes |
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
Example #17
Source File: test_inspect.py From CTFCrackTools with GNU General Public License v3.0 | 5 votes |
def test_findsource_binary(self): self.assertRaises(IOError, inspect.getsource, unicodedata) self.assertRaises(IOError, inspect.findsource, unicodedata)
Example #18
Source File: test_inspect.py From CTFCrackTools with GNU General Public License v3.0 | 5 votes |
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])
Example #19
Source File: test_inspect.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_findsource_code_in_linecache(self): lines = ["x=1"] co = compile(lines[0], "_dynamically_created_file", "exec") self.assertRaises(OSError, inspect.findsource, co) self.assertRaises(OSError, 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]
Example #20
Source File: test_inspect.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_findsource_code_in_linecache(self): lines = ["x=1"] co = compile(lines[0], "_dynamically_created_file", "exec") self.assertRaises(OSError, inspect.findsource, co) self.assertRaises(OSError, 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]
Example #21
Source File: test_inspect.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_findsource_binary(self): self.assertRaises(OSError, inspect.getsource, unicodedata) self.assertRaises(OSError, inspect.findsource, unicodedata)
Example #22
Source File: pdb.py From ironpython3 with Apache License 2.0 | 5 votes |
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
Example #23
Source File: pdb.py From Imogen with MIT License | 5 votes |
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
Example #24
Source File: conf.py From txacme with MIT License | 5 votes |
def linkcode_resolve(domain, info): """ Determine the URL corresponding to Python object """ if domain != 'py': return None modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return None obj = submod for part in fullname.split('.'): try: obj = getattr(obj, part) except: return None try: fn = inspect.getsourcefile(obj) except: fn = None if not fn: return None try: source, lineno = inspect.findsource(obj) except: lineno = None if lineno: linespec = "#L%d" % (lineno + 1) else: linespec = "" fn = relpath(fn, start='..') return "https://github.com/mithrandi/txacme/blob/%s/%s%s" % ( txacme_version_info['full-revisionid'], fn, linespec)
Example #25
Source File: test_inspect.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
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)
Example #26
Source File: test_inspect.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_findsource_code_in_linecache(self): lines = ["x=1"] co = compile(lines[0], "_dynamically_created_file", "exec") self.assertRaises(OSError, inspect.findsource, co) self.assertRaises(OSError, 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]
Example #27
Source File: test_inspect.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_findsource_binary(self): self.assertRaises(OSError, inspect.getsource, unicodedata) self.assertRaises(OSError, inspect.findsource, unicodedata)
Example #28
Source File: pdb.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
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
Example #29
Source File: extraction.py From stackprinter with MIT License | 5 votes |
def get_source(frame): """ get source lines for this frame Params --- frame : frame object Returns --- lines : list of str startline : int location of lines[0] in the original source file """ # TODO find out what's faster: Allowing inspect's getsourcelines # to tokenize the whole file to find the surrounding code block, # or getting the whole file quickly via linecache & feeding all # of it to our own instance of tokenize, then clipping to # desired context afterwards. if frame.f_code.co_name in NON_FUNCTION_SCOPES: lines, _ = inspect.findsource(frame) startline = 1 else: lines, startline = inspect.getsourcelines(frame) return lines, startline
Example #30
Source File: test_source.py From pytest with MIT License | 5 votes |
def test_getfslineno() -> None: def f(x) -> None: raise NotImplementedError() fspath, lineno = getfslineno(f) assert isinstance(fspath, py.path.local) assert fspath.basename == "test_source.py" assert lineno == f.__code__.co_firstlineno - 1 # see findsource class A: pass fspath, lineno = getfslineno(A) _, A_lineno = inspect.findsource(A) assert isinstance(fspath, py.path.local) assert fspath.basename == "test_source.py" assert lineno == A_lineno assert getfslineno(3) == ("", -1) class B: pass B.__name__ = B.__qualname__ = "B2" assert getfslineno(B)[1] == -1 co = compile("...", "", "eval") assert co.co_filename == "" if hasattr(sys, "pypy_version_info"): assert getfslineno(co) == ("", -1) else: assert getfslineno(co) == ("", 0)