Python inspect.getsource() Examples

The following are 30 code examples of inspect.getsource(). 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 .
Example #1
Source File: OptiProblem.py    From pyleecan with Apache License 2.0 6 votes vote down vote up
def _set_eval_func(self, value):
        """setter of eval_func"""
        try:
            check_var("eval_func", value, "list")
        except CheckTypeError:
            check_var("eval_func", value, "function")
        if isinstance(value, list):  # Load function from saved dict
            self._eval_func = [loads(value[0].encode("ISO-8859-2")), value[1]]
        elif value is None:
            self._eval_func = [None, None]
        elif callable(value):
            self._eval_func = [value, getsource(value)]
        else:
            raise TypeError(
                "Expected function or list from a saved file, got: " + str(type(value))
            )

    # Function to evaluate before computing obj function and constraints
    # Type : function 
Example #2
Source File: typing.py    From pytorch_geometric with MIT License 6 votes vote down vote up
def parse_types(func: Callable) -> List[Tuple[Dict[str, str], str]]:
    source = inspect.getsource(func)
    signature = inspect.signature(func)

    # Parse `# type: (...) -> ...` annotation. Note that it is allowed to pass
    # multiple `# type:` annotations in `forward()`.
    iterator = re.finditer(r'#\s*type:\s*\((.*)\)\s*->\s*(.*)\s*\n', source)
    matches = list(iterator)

    if len(matches) > 0:
        out = []
        args = list(signature.parameters.keys())
        for match in matches:
            arg_types_repr, return_type = match.groups()
            arg_types = split_types_repr(arg_types_repr)
            arg_types = OrderedDict((k, v) for k, v in zip(args, arg_types))
            return_type = return_type.split('#')[0].strip()
            out.append((arg_types, return_type))
        return out

    # Alternatively, parse annotations using the inspected signature.
    else:
        ps = signature.parameters
        arg_types = OrderedDict((k, param_type_repr(v)) for k, v in ps.items())
        return [(arg_types, return_type_repr(signature))] 
Example #3
Source File: test_inspect.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_proceed_with_fake_filename(self):
        '''doctest monkeypatches linecache to enable inspection'''
        fn, source = '<test>', 'def x(): pass\n'
        getlines = linecache.getlines
        def monkey(filename, module_globals=None):
            if filename == fn:
                return source.splitlines(True)
            else:
                return getlines(filename, module_globals)
        linecache.getlines = monkey
        try:
            ns = {}
            exec compile(source, fn, 'single') in ns
            inspect.getsource(ns["x"])
        finally:
            linecache.getlines = getlines 
Example #4
Source File: test_docstring_parameters.py    From celer with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_tabs():
    """Test that there are no tabs in our source files."""
    ignore = _tab_ignores[:]

    for importer, modname, ispkg in walk_packages(celer.__path__,
                                                  prefix='celer.'):
        if not ispkg and modname not in ignore:
            # mod = importlib.import_module(modname)  # not py26 compatible!
            try:
                with warnings.catch_warnings(record=True):  # traits
                    __import__(modname)
            except Exception:  # can't import properly
                continue
            mod = sys.modules[modname]
            try:
                source = getsource(mod)
            except IOError:  # user probably should have run "make clean"
                continue
            assert '\t' not in source, ('"%s" has tabs, please remove them '
                                        'or add it to the ignore list'
                                        % modname) 
Example #5
Source File: ast_preprocess.py    From neo-boa with MIT License 6 votes vote down vote up
def preprocess_method_body(source_code_obj):

    src = inspect.getsource(source_code_obj)

    ast_tree = ast.parse(src)

    visitor = RewriteDicts()
    ast_tree = visitor.visit(ast_tree)

    ast.fix_missing_locations(ast_tree)
    updated_code = compile(ast_tree, filename='<ast>', mode='exec')
    bc = Bytecode.from_code(updated_code)

    dlist = visitor.updated_dicts
    RewriteDicts.updated_dicts = []
    RewriteDicts.last_store_name = None

    block_code = get_code_block(bc)
    return block_code.arg, dlist 
Example #6
Source File: builder_test.py    From lingvo with Apache License 2.0 6 votes vote down vote up
def testSymbolicDims(self):
    p = builder.Base.Params()
    b = p.Instantiate()

    f1 = tshape.Shape(['kh', 'kw', 'idims', 'odims'])
    kh, kw, idims, odims = f1
    f2 = tshape.Shape([kh, kw, odims, odims])
    p = b._Seq('test', b._Conv2D('conv', f1, (2, 2)),
               b._Conv2D('conv', f2, (2, 2)), b._Bias('bias', odims))

    inp = tshape.Shape(['b', 'h', 'w', idims])
    b, h, w, _ = inp
    meta = p.cls.FPropMeta(p, inp)
    print('flops = ', meta.flops)
    out = meta.out_shapes[0]
    print('outputs = ', out)

    # sympy.lambdify can help us to do faster numerical evaluation.
    # Might be useful to build a "cost" model given a builder layer.
    f = sympy.lambdify([b, h, w, kh, kw, idims, odims], meta.flops, 'numpy')
    print('f.source = ', inspect.getsource(f))
    self.assertEqual(f(8, 224, 224, 3, 3, 8, 32), 925646848)
    self.assertEqual(f(8, 224, 224, 5, 5, 8, 32), 2569814016) 
Example #7
Source File: test_source.py    From py with MIT License 6 votes vote down vote up
def test_deindent():
    from py._code.source import deindent as deindent
    assert deindent(['\tfoo', '\tbar', ]) == ['foo', 'bar']

    def f():
        c = '''while True:
    pass
'''
    import inspect
    lines = deindent(inspect.getsource(f).splitlines())
    assert lines == ["def f():", "    c = '''while True:", "    pass", "'''"]

    source = """
        def f():
            def g():
                pass
    """
    lines = deindent(source.splitlines())
    assert lines == ['', 'def f():', '    def g():', '        pass', '    '] 
Example #8
Source File: pdbpp.py    From pdbpp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _install_linecache_wrapper(self):
        """Disable linecache.checkcache to not invalidate caches.

        This gets installed permanently to also bypass e.g. pytest using
        `inspect.getsource`, which would invalidate it outside of the
        interaction them.
        """
        if not hasattr(self, "_orig_linecache_checkcache"):
            import linecache

            # Save it, although not used really (can be useful for debugging).
            self._orig_linecache_checkcache = linecache.checkcache

            def _linecache_checkcache(*args, **kwargs):
                return

            linecache.checkcache = _linecache_checkcache 
Example #9
Source File: source.py    From python-netsurv with MIT License 6 votes vote down vote up
def __init__(self, *parts, **kwargs):
        self.lines = lines = []
        de = kwargs.get("deindent", True)
        for part in parts:
            if not part:
                partlines = []
            elif isinstance(part, Source):
                partlines = part.lines
            elif isinstance(part, (tuple, list)):
                partlines = [x.rstrip("\n") for x in part]
            elif isinstance(part, str):
                partlines = part.split("\n")
            else:
                partlines = getsource(part, deindent=de).lines
            if de:
                partlines = deindent(partlines)
            lines.extend(partlines) 
Example #10
Source File: source.py    From py with MIT License 6 votes vote down vote up
def __init__(self, *parts, **kwargs):
        self.lines = lines = []
        de = kwargs.get('deindent', True)
        rstrip = kwargs.get('rstrip', True)
        for part in parts:
            if not part:
                partlines = []
            if isinstance(part, Source):
                partlines = part.lines
            elif isinstance(part, (tuple, list)):
                partlines = [x.rstrip("\n") for x in part]
            elif isinstance(part, py.builtin._basestring):
                partlines = part.split('\n')
                if rstrip:
                    while partlines:
                        if partlines[-1].strip():
                            break
                        partlines.pop()
            else:
                partlines = getsource(part, deindent=de).lines
            if de:
                partlines = deindent(partlines)
            lines.extend(partlines) 
Example #11
Source File: source.py    From python-netsurv with MIT License 6 votes vote down vote up
def __init__(self, *parts, **kwargs):
        self.lines = lines = []
        de = kwargs.get('deindent', True)
        rstrip = kwargs.get('rstrip', True)
        for part in parts:
            if not part:
                partlines = []
            if isinstance(part, Source):
                partlines = part.lines
            elif isinstance(part, (tuple, list)):
                partlines = [x.rstrip("\n") for x in part]
            elif isinstance(part, py.builtin._basestring):
                partlines = part.split('\n')
                if rstrip:
                    while partlines:
                        if partlines[-1].strip():
                            break
                        partlines.pop()
            else:
                partlines = getsource(part, deindent=de).lines
            if de:
                partlines = deindent(partlines)
            lines.extend(partlines) 
Example #12
Source File: tfutil.py    From disentangling_conditional_gans with MIT License 6 votes vote down vote up
def __init__(self,
        name=None,          # Network name. Used to select TensorFlow name and variable scopes.
        func=None,          # Fully qualified name of the underlying network construction function.
        **static_kwargs):   # Keyword arguments to be passed in to the network construction function.

        self._init_fields()
        self.name = name
        self.static_kwargs = dict(static_kwargs)

        # Init build func.
        module, self._build_func_name = import_module(func)
        self._build_module_src = inspect.getsource(module)
        self._build_func = find_obj_in_module(module, self._build_func_name)

        # Init graph.
        self._init_graph()
        self.reset_vars() 
Example #13
Source File: source.py    From python-netsurv with MIT License 6 votes vote down vote up
def __init__(self, *parts, **kwargs):
        self.lines = lines = []
        de = kwargs.get("deindent", True)
        for part in parts:
            if not part:
                partlines = []
            elif isinstance(part, Source):
                partlines = part.lines
            elif isinstance(part, (tuple, list)):
                partlines = [x.rstrip("\n") for x in part]
            elif isinstance(part, str):
                partlines = part.split("\n")
            else:
                partlines = getsource(part, deindent=de).lines
            if de:
                partlines = deindent(partlines)
            lines.extend(partlines) 
Example #14
Source File: functions.py    From chainer-compiler with MIT License 6 votes vote down vote up
def __init__(self, func):
        super().__init__()

        self.inst = func
        self.name = func.__name__
        self.filename = inspect.getfile(func)
        sourcelines = inspect.getsourcelines(func)
        self.lineno = sourcelines[1]
        self.args.analyze_args(func)

        if (func.__name__ == (lambda: None).__name__):
            original_code = utils.lambda_source(func)
            code = 'return ' + original_code[re.search('lambda.*?:', original_code).end():]
            self.ast = gast.ast_to_gast(ast.parse(code))
        else:
            original_code = inspect.getsource(func)
            code = utils.clip_head(original_code)
            ast_ = gast.ast_to_gast(ast.parse(code)).body[0]
            self.ast = canonicalizer.Canonicalizer().visit(ast_) 
Example #15
Source File: _Waiter.py    From myhdl with GNU Lesser General Public License v2.1 6 votes vote down vote up
def _inferWaiter(gen):
    f = gen.gi_frame
    s = inspect.getsource(f)
    s = _dedent(s)
    root = ast.parse(s)
    root.symdict = f.f_globals.copy()
    root.symdict.update(f.f_locals)
    # print ast.dump(root)
    v = _YieldVisitor(root)
    v.visit(root)
    if v.kind == _kind.EDGE_TUPLE:
        return _EdgeTupleWaiter(gen)
    if v.kind == _kind.SIGNAL_TUPLE:
        return _SignalTupleWaiter(gen)
    if v.kind == _kind.DELAY:
        return _DelayWaiter(gen)
    if v.kind == _kind.EDGE:
        return _EdgeWaiter(gen)
    if v.kind == _kind.SIGNAL:
        return _SignalWaiter(gen)
    # default
    return _Waiter(gen) 
Example #16
Source File: _util.py    From myhdl with GNU Lesser General Public License v2.1 6 votes vote down vote up
def _makeAST(f):
    # Need to look at the flags used to compile the original function f and
    # pass these same flags to the compile() function. This ensures that
    # syntax-changing __future__ imports like print_function work correctly.
    orig_f_co_flags = f.__code__.co_flags
    # co_flags can contain various internal flags that we can't pass to
    # compile(), so strip them out here
    valid_flags = 0
    for future_feature in __future__.all_feature_names:
        feature = getattr(__future__, future_feature)
        valid_flags |= feature.compiler_flag
    s = inspect.getsource(f)
    s = _dedent(s)
    # use compile instead of ast.parse so that additional flags can be passed
    flags = ast.PyCF_ONLY_AST | (orig_f_co_flags & valid_flags)
    tree = compile(s, filename='<unknown>', mode='exec',
        flags=flags, dont_inherit=True)
    # tree = ast.parse(s)
    tree.sourcefile = inspect.getsourcefile(f)
    tree.lineoffset = inspect.getsourcelines(f)[1] - 1
    return tree 
Example #17
Source File: OptiGenAlg.py    From pyleecan with Apache License 2.0 6 votes vote down vote up
def _set_mutator(self, value):
        """setter of mutator"""
        try:
            check_var("mutator", value, "list")
        except CheckTypeError:
            check_var("mutator", value, "function")
        if isinstance(value, list):  # Load function from saved dict
            self._mutator = [loads(value[0].encode("ISO-8859-2")), value[1]]
        elif value is None:
            self._mutator = [None, None]
        elif callable(value):
            self._mutator = [value, getsource(value)]
        else:
            raise TypeError(
                "Expected function or list from a saved file, got: " + str(type(value))
            )

    # Mutator of the genetic algorithm
    # Type : function 
Example #18
Source File: OptiGenAlg.py    From pyleecan with Apache License 2.0 6 votes vote down vote up
def _set_crossover(self, value):
        """setter of crossover"""
        try:
            check_var("crossover", value, "list")
        except CheckTypeError:
            check_var("crossover", value, "function")
        if isinstance(value, list):  # Load function from saved dict
            self._crossover = [loads(value[0].encode("ISO-8859-2")), value[1]]
        elif value is None:
            self._crossover = [None, None]
        elif callable(value):
            self._crossover = [value, getsource(value)]
        else:
            raise TypeError(
                "Expected function or list from a saved file, got: " + str(type(value))
            )

    # Crossover of the genetic algorithm
    # Type : function 
Example #19
Source File: OptiGenAlg.py    From pyleecan with Apache License 2.0 6 votes vote down vote up
def _set_selector(self, value):
        """setter of selector"""
        try:
            check_var("selector", value, "list")
        except CheckTypeError:
            check_var("selector", value, "function")
        if isinstance(value, list):  # Load function from saved dict
            self._selector = [loads(value[0].encode("ISO-8859-2")), value[1]]
        elif value is None:
            self._selector = [None, None]
        elif callable(value):
            self._selector = [value, getsource(value)]
        else:
            raise TypeError(
                "Expected function or list from a saved file, got: " + str(type(value))
            )

    # Selector of the genetic algorithm
    # Type : function 
Example #20
Source File: OptiDesignVar.py    From pyleecan with Apache License 2.0 6 votes vote down vote up
def _set_function(self, value):
        """setter of function"""
        try:
            check_var("function", value, "list")
        except CheckTypeError:
            check_var("function", value, "function")
        if isinstance(value, list):  # Load function from saved dict
            self._function = [loads(value[0].encode("ISO-8859-2")), value[1]]
        elif value is None:
            self._function = [None, None]
        elif callable(value):
            self._function = [value, getsource(value)]
        else:
            raise TypeError(
                "Expected function or list from a saved file, got: " + str(type(value))
            )

    # Function of the space to initiate the variable
    # Type : function 
Example #21
Source File: source.py    From python-netsurv with MIT License 6 votes vote down vote up
def __init__(self, *parts, **kwargs):
        self.lines = lines = []
        de = kwargs.get('deindent', True)
        rstrip = kwargs.get('rstrip', True)
        for part in parts:
            if not part:
                partlines = []
            if isinstance(part, Source):
                partlines = part.lines
            elif isinstance(part, (tuple, list)):
                partlines = [x.rstrip("\n") for x in part]
            elif isinstance(part, py.builtin._basestring):
                partlines = part.split('\n')
                if rstrip:
                    while partlines:
                        if partlines[-1].strip():
                            break
                        partlines.pop()
            else:
                partlines = getsource(part, deindent=de).lines
            if de:
                partlines = deindent(partlines)
            lines.extend(partlines) 
Example #22
Source File: source.py    From python-netsurv with MIT License 5 votes vote down vote up
def getsource(obj, **kwargs):
    obj = py.code.getrawcode(obj)
    try:
        strsrc = inspect.getsource(obj)
    except IndentationError:
        strsrc = "\"Buggy python version consider upgrading, cannot get source\""
    assert isinstance(strsrc, str)
    return Source(strsrc, **kwargs) 
Example #23
Source File: test_zipimport.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def assertModuleSource(self, module):
        self.assertEqual(inspect.getsource(module), test_src) 
Example #24
Source File: test_zipimport_support.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_inspect_getsource_issue4223(self):
        test_src = "def foo(): pass\n"
        with temp_dir() as d:
            init_name = make_script(d, '__init__', test_src)
            name_in_zip = os.path.join('zip_pkg',
                                       os.path.basename(init_name))
            zip_name, run_name = make_zip_script(d, 'test_zip',
                                                init_name, name_in_zip)
            os.remove(init_name)
            sys.path.insert(0, zip_name)
            import zip_pkg
            self.assertEqual(inspect.getsource(zip_pkg.foo), test_src) 
Example #25
Source File: schema.py    From zvt with MIT License 5 votes vote down vote up
def help(cls):
        print(inspect.getsource(cls)) 
Example #26
Source File: tf_inspect.py    From lambda-packs with MIT License 5 votes vote down vote up
def getsource(object):  # pylint: disable=redefined-builtin
  """TFDecorator-aware replacement for inspect.getsource."""
  return _inspect.getsource(tf_decorator.unwrap(object)[1]) 
Example #27
Source File: test_inspect.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def assertSourceEqual(self, obj, top, bottom):
        self.assertEqual(inspect.getsource(obj),
                         self.sourcerange(top, bottom)) 
Example #28
Source File: util.py    From rlgraph with Apache License 2.0 5 votes vote down vote up
def strip_source_code(method, remove_nested_functions=True):
    """
    Strips the source code of a method by everything that's "not important", like comments.

    Args:
        method (Union[callable,str]): The method to strip the source code for (or the source code directly as string).
        remove_nested_functions (bool): Whether to remove nested functions from the source code as well.
            These usually confuse the analysis of a method's source code as they comprise a method within a method.

    Returns:
        str: The stripped source code.
    """
    if callable(method):
        src = inspect.getsource(method)
    else:
        src = method

    # Resolve '\' at end of lines.
    src = re.sub(r'\\\s*\n', "", src)
    # Remove single line comments.
    src = re.sub(r'\n\s*#.+', "", src)
    # Remove multi-line comments.
    src = re.sub(r'"""(.|\n)*?"""', "", src)
    # Remove nested functions.
    if remove_nested_functions is True:
        src = re.sub(r'\n(\s*)def \w+\((.|\n)+?\n\1[^\s\n]', "", src)

    return src 
Example #29
Source File: network.py    From ai-platform with MIT License 5 votes vote down vote up
def __init__(self, name: str = None, func_name: Any = None, **static_kwargs):
        tfutil.assert_tf_initialized()
        assert isinstance(name, str) or name is None
        assert func_name is not None
        assert isinstance(func_name, str) or util.is_top_level_function(func_name)
        assert util.is_pickleable(static_kwargs)

        self._init_fields()
        self.name = name
        self.static_kwargs = util.EasyDict(static_kwargs)

        # Locate the user-specified network build function.
        if util.is_top_level_function(func_name):
            func_name = util.get_top_level_function_name(func_name)
        module, self._build_func_name = util.get_module_from_obj_name(func_name)
        self._build_func = util.get_obj_from_module(module, self._build_func_name)
        assert callable(self._build_func)

        # Dig up source code for the module containing the build function.
        self._build_module_src = _import_module_src.get(module, None)
        if self._build_module_src is None:
            self._build_module_src = inspect.getsource(module)

        # Init TensorFlow graph.
        self._init_graph()
        self.reset_own_vars() 
Example #30
Source File: chainer2onnx.py    From chainer-compiler with MIT License 5 votes vote down vote up
def __init__(self, ch, fn):
        self.ch = ch
        src = clip_head(inspect.getsource(fn))
        dprint(src)
        self.ast = gast.ast_to_gast(ast.parse(src)).body[0]
        assert(isinstance(self.ast, gast.gast.FunctionDef))