当前位置: 首页>>代码示例>>Python>>正文


Python inspect.getsource方法代码示例

本文整理汇总了Python中inspect.getsource方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.getsource方法的具体用法?Python inspect.getsource怎么用?Python inspect.getsource使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在inspect的用法示例。


在下文中一共展示了inspect.getsource方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsource [as 别名]
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() 
开发者ID:zalandoresearch,项目名称:disentangling_conditional_gans,代码行数:19,代码来源:tfutil.py

示例2: _inferWaiter

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsource [as 别名]
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) 
开发者ID:myhdl,项目名称:myhdl,代码行数:24,代码来源:_Waiter.py

示例3: _makeAST

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsource [as 别名]
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 
开发者ID:myhdl,项目名称:myhdl,代码行数:23,代码来源:_util.py

示例4: __init__

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsource [as 别名]
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) 
开发者ID:pytest-dev,项目名称:py,代码行数:25,代码来源:source.py

示例5: test_deindent

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsource [as 别名]
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', '    '] 
开发者ID:pytest-dev,项目名称:py,代码行数:21,代码来源:test_source.py

示例6: test_tabs

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsource [as 别名]
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) 
开发者ID:mathurinm,项目名称:celer,代码行数:23,代码来源:test_docstring_parameters.py

示例7: parse_types

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsource [as 别名]
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))] 
开发者ID:rusty1s,项目名称:pytorch_geometric,代码行数:27,代码来源:typing.py

示例8: preprocess_method_body

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsource [as 别名]
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 
开发者ID:CityOfZion,项目名称:neo-boa,代码行数:21,代码来源:ast_preprocess.py

示例9: testSymbolicDims

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsource [as 别名]
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) 
开发者ID:tensorflow,项目名称:lingvo,代码行数:25,代码来源:builder_test.py

示例10: _install_linecache_wrapper

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsource [as 别名]
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 
开发者ID:pdbpp,项目名称:pdbpp,代码行数:19,代码来源:pdbpp.py

示例11: __init__

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsource [as 别名]
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) 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:19,代码来源:source.py

示例12: test_proceed_with_fake_filename

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsource [as 别名]
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 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:18,代码来源:test_inspect.py

示例13: __init__

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsource [as 别名]
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_) 
开发者ID:pfnet-research,项目名称:chainer-compiler,代码行数:21,代码来源:functions.py

示例14: _set_function

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsource [as 别名]
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 
开发者ID:Eomys,项目名称:pyleecan,代码行数:21,代码来源:OptiDesignVar.py

示例15: _set_selector

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsource [as 别名]
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 
开发者ID:Eomys,项目名称:pyleecan,代码行数:21,代码来源:OptiGenAlg.py


注:本文中的inspect.getsource方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。