當前位置: 首頁>>代碼示例>>Python>>正文


Python ast.Assign方法代碼示例

本文整理匯總了Python中ast.Assign方法的典型用法代碼示例。如果您正苦於以下問題:Python ast.Assign方法的具體用法?Python ast.Assign怎麽用?Python ast.Assign使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在ast的用法示例。


在下文中一共展示了ast.Assign方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: version

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Assign [as 別名]
def version():
    path = 'pypika/__init__.py'
    with open(path, 'r') as file:
        t = compile(file.read(), path, 'exec', ast.PyCF_ONLY_AST)
        for node in (n for n in t.body if isinstance(n, ast.Assign)):
            if len(node.targets) == 1:
                name = node.targets[0]
                if isinstance(name, ast.Name) and \
                      name.id in ('__version__', '__version_info__', 'VERSION'):
                    v = node.value
                    if isinstance(v, ast.Str):
                        return v.s

                    if isinstance(v, ast.Tuple):
                        r = []
                        for e in v.elts:
                            if isinstance(e, ast.Str):
                                r.append(e.s)
                            elif isinstance(e, ast.Num):
                                r.append(str(e.n))
                        return '.'.join(r) 
開發者ID:kayak,項目名稱:pypika,代碼行數:23,代碼來源:setup.py

示例2: visit_FunctionDef

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Assign [as 別名]
def visit_FunctionDef(self, node):
        self.refStack.push()
        for n in node.body:
            self.visit(n)
        self.tree.kind = _kind.SIMPLE_ALWAYS_COMB
        for n in node.body:
            if isinstance(n, ast.Expr) and isinstance(n.value, ast.Str):
                continue  # skip doc strings
            if isinstance(n, ast.Assign) and \
               isinstance(n.targets[0], ast.Attribute) and \
               self.getKind(n.targets[0].value) != _kind.REG:
                pass
            else:
                self.tree.kind = _kind.ALWAYS_COMB
                return
        # rom access is expanded into a case statement in addition
        # to any always_comb that contains a list of signals
        # if self.tree.hasRom or self.tree.hasLos:
        if self.tree.hasRom:
            self.tree.kind = _kind.ALWAYS_COMB
        self.refStack.pop() 
開發者ID:myhdl,項目名稱:myhdl,代碼行數:23,代碼來源:_analyze.py

示例3: expr_stmt_rewrite

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Assign [as 別名]
def expr_stmt_rewrite(lhs, ann, aug, aug_exp, rhs: t.Optional[list]):
    if rhs:
        as_store(lhs)
        *init, end = rhs
        for each in init:
            as_store(each)
        return ast.Assign([lhs, *init], end)

    if ann:
        as_store(lhs)
        anno, value = ann
        return ast.AnnAssign(lhs, anno, value, 1)

    if aug_exp:
        as_store(lhs)
        return ast.AugAssign(lhs, aug(), aug_exp)

    # NO AS STORE HERE!
    return ast.Expr(lhs) 
開發者ID:Xython,項目名稱:YAPyPy,代碼行數:21,代碼來源:helper.py

示例4: get_config_comments

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Assign [as 別名]
def get_config_comments(func):
    filename = inspect.getfile(func)
    func_body, line_offset = get_function_body(func)
    body_source = dedent_function_body(func_body)
    body_code = compile(body_source, filename, "exec", ast.PyCF_ONLY_AST)
    body_lines = body_source.split("\n")

    variables = {"seed": "the random seed for this experiment"}

    for ast_root in body_code.body:
        for ast_entry in [ast_root] + list(ast.iter_child_nodes(ast_root)):
            if isinstance(ast_entry, ast.Assign):
                # we found an assignment statement
                # go through all targets of the assignment
                # usually a single entry, but can be more for statements like:
                # a = b = 5
                for t in ast_entry.targets:
                    add_doc(t, variables, body_lines)

    return variables 
開發者ID:IDSIA,項目名稱:sacred,代碼行數:22,代碼來源:config_scope.py

示例5: pop_format_context

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Assign [as 別名]
def pop_format_context(self, expl_expr):
        """Format the %-formatted string with current format context.

        The expl_expr should be an ast.Str instance constructed from
        the %-placeholders created by .explanation_param().  This will
        add the required code to format said string to .expl_stmts and
        return the ast.Name instance of the formatted string.

        """
        current = self.stack.pop()
        if self.stack:
            self.explanation_specifiers = self.stack[-1]
        keys = [ast.Str(key) for key in current.keys()]
        format_dict = ast.Dict(keys, list(current.values()))
        form = ast.BinOp(expl_expr, ast.Mod(), format_dict)
        name = "@py_format" + str(next(self.variable_counter))
        if self.enable_assertion_pass_hook:
            self.format_variables.append(name)
        self.expl_stmts.append(ast.Assign([ast.Name(name, ast.Store())], form))
        return ast.Name(name, ast.Load()) 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:22,代碼來源:rewrite.py

示例6: test_with_src_module_file

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Assign [as 別名]
def test_with_src_module_file():
    poetry = Factory().create_poetry(project("source_file"))

    builder = SdistBuilder(poetry, NullEnv(), NullIO())

    # Check setup.py
    setup = builder.build_setup()
    setup_ast = ast.parse(setup)

    setup_ast.body = [n for n in setup_ast.body if isinstance(n, ast.Assign)]
    ns = {}
    exec(compile(setup_ast, filename="setup.py", mode="exec"), ns)
    assert ns["package_dir"] == {"": "src"}
    assert ns["modules"] == ["module_src"]

    builder.build()

    sdist = fixtures_dir / "source_file" / "dist" / "module-src-0.1.tar.gz"

    assert sdist.exists()

    with tarfile.open(str(sdist), "r") as tar:
        assert "module-src-0.1/src/module_src.py" in tar.getnames() 
開發者ID:python-poetry,項目名稱:poetry,代碼行數:25,代碼來源:test_sdist.py

示例7: test_with_src_module_dir

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Assign [as 別名]
def test_with_src_module_dir():
    poetry = Factory().create_poetry(project("source_package"))

    builder = SdistBuilder(poetry, NullEnv(), NullIO())

    # Check setup.py
    setup = builder.build_setup()
    setup_ast = ast.parse(setup)

    setup_ast.body = [n for n in setup_ast.body if isinstance(n, ast.Assign)]
    ns = {}
    exec(compile(setup_ast, filename="setup.py", mode="exec"), ns)
    assert ns["package_dir"] == {"": "src"}
    assert ns["packages"] == ["package_src"]

    builder.build()

    sdist = fixtures_dir / "source_package" / "dist" / "package-src-0.1.tar.gz"

    assert sdist.exists()

    with tarfile.open(str(sdist), "r") as tar:
        assert "package-src-0.1/src/package_src/__init__.py" in tar.getnames()
        assert "package-src-0.1/src/package_src/module.py" in tar.getnames() 
開發者ID:python-poetry,項目名稱:poetry,代碼行數:26,代碼來源:test_sdist.py

示例8: _find_variable_in_body

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Assign [as 別名]
def _find_variable_in_body(
        self, body, name
    ):  # type: (Iterable[Any], str) -> Optional[Any]
        found = None
        for elem in body:
            if found:
                break

            if not isinstance(elem, ast.Assign):
                continue

            for target in elem.targets:
                if not isinstance(target, ast.Name):
                    continue

                if target.id == name:
                    return elem.value 
開發者ID:frostming,項目名稱:pdm,代碼行數:19,代碼來源:readers.py

示例9: get_version

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Assign [as 別名]
def get_version(fname):
    """Get the version info from the mpld3 package without importing it"""
    import ast

    with open(fname) as init_file:
        module = ast.parse(init_file.read())

    version = (ast.literal_eval(node.value) for node in ast.walk(module)
               if isinstance(node, ast.Assign)
               and node.targets[0].id == "__version__")
    try:
        return next(version)
    except StopIteration:
        raise ValueError("version could not be located")


#cffi.verifier.cleanup_tmpdir() 
開發者ID:brentp,項目名稱:hts-python,代碼行數:19,代碼來源:setup.py

示例10: visit_Return

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Assign [as 別名]
def visit_Return(self, return_):
        """Convert returns into assignment/exception pairs

        Since the body of this function will be in the global namespace we
        can't have any returns. An acceptable alternative is to set a variable
        called 'RETURN' and then immediately raise an exception.

        >>> self = NamespacePromoter(buffer='foo')
        >>> code = '''
        ...
        ... return 5
        ...
        ... '''
        >>> tree = ast.parse(code)
        >>> return_, = tree.body

        """
        nodes = [
            ast.Assign(targets=[ast.Name(id='RETURN', ctx=ast.Store())], value=return_.value, lineno=return_.lineno),
            ast.Raise(exc=ast.Call(func=ast.Name(id='Exception', ctx=ast.Load()), args=[ast.Str(s='return')], keywords=[]), cause=None),
        ]
        return nodes 
開發者ID:ebanner,項目名稱:pynt,代碼行數:24,代碼來源:node_transformers.py

示例11: _fine_property_definition

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Assign [as 別名]
def _fine_property_definition(self, property_name):
        """Find the lines in the source code that contain this property's name and definition.

        This function can find both attribute assignments as well as methods/functions.

        Args:
            property_name (str): the name of the property to look up in the template definition

        Returns:
            tuple: line numbers for the start and end of the attribute definition
        """
        for node in ast.walk(ast.parse(self._source)):
            if isinstance(node, ast.Assign) and node.targets[0].id == property_name:
                return node.targets[0].lineno - 1, self._get_node_line_end(node)
            elif isinstance(node, ast.FunctionDef) and node.name == property_name:
                return node.lineno - 1, self._get_node_line_end(node)
        raise ValueError('The requested node could not be found.') 
開發者ID:robbert-harms,項目名稱:MDT,代碼行數:19,代碼來源:utils.py

示例12: pop_format_context

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Assign [as 別名]
def pop_format_context(self, expl_expr: ast.expr) -> ast.Name:
        """Format the %-formatted string with current format context.

        The expl_expr should be an str ast.expr instance constructed from
        the %-placeholders created by .explanation_param().  This will
        add the required code to format said string to .expl_stmts and
        return the ast.Name instance of the formatted string.

        """
        current = self.stack.pop()
        if self.stack:
            self.explanation_specifiers = self.stack[-1]
        keys = [ast.Str(key) for key in current.keys()]
        format_dict = ast.Dict(keys, list(current.values()))
        form = ast.BinOp(expl_expr, ast.Mod(), format_dict)
        name = "@py_format" + str(next(self.variable_counter))
        if self.enable_assertion_pass_hook:
            self.format_variables.append(name)
        self.expl_stmts.append(ast.Assign([ast.Name(name, ast.Store())], form))
        return ast.Name(name, ast.Load()) 
開發者ID:pytest-dev,項目名稱:pytest,代碼行數:22,代碼來源:rewrite.py

示例13: _parse_setup_params

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Assign [as 別名]
def _parse_setup_params(setup_py: Path) -> Dict[str, Any]:
    with setup_py.open("r", encoding="utf8") as sp:
        setup_tree = ast.parse(sp.read())

    LOG.debug(f"AST visiting {setup_py}")
    for node in ast.walk(setup_tree):
        if isinstance(node, ast.Assign):
            for target in node.targets:
                target_id = getattr(target, "id", None)
                if not target_id:
                    continue

                if target_id == "ptr_params":
                    LOG.debug(f"Found ptr_params in {setup_py}")
                    return dict(ast.literal_eval(node.value))
    return {} 
開發者ID:facebookincubator,項目名稱:ptr,代碼行數:18,代碼來源:ptr.py

示例14: read_tags

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Assign [as 別名]
def read_tags(filename):
    """Reads values of "magic tags" defined in the given Python file.

    :param filename: Python filename to read the tags from
    :return: Dictionary of tags
    """
    with open(filename) as f:
        ast_tree = ast.parse(f.read(), filename)

    res = {}
    for node in ast.walk(ast_tree):
        if type(node) is not ast.Assign:
            continue

        target = node.targets[0]
        if type(target) is not ast.Name:
            continue
        if not (target.id.startswith('__') and target.id.endswith('__')):
            continue

        name = target.id[2:-2]
        res[name] = ast.literal_eval(node.value)

    return res 
開發者ID:Xion,項目名稱:callee,代碼行數:26,代碼來源:setup.py

示例15: assign_multi_target

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Assign [as 別名]
def assign_multi_target(self, node, right_hand_side_variables):
        new_assignment_nodes = list()

        for target in node.targets:
            label = LabelVisitor()
            label.visit(target)
            left_hand_side = label.result
            label.result += ' = '
            label.visit(node.value)
            new_assignment_nodes.append(self.append_node(AssignmentNode(
                label.result,
                left_hand_side,
                ast.Assign(target, node.value),
                right_hand_side_variables,
                line_number=node.lineno,
                path=self.filenames[-1]
            )))

        connect_nodes(new_assignment_nodes)
        return ControlFlowNode(new_assignment_nodes[0], [new_assignment_nodes[-1]], [])  # return the last added node 
開發者ID:python-security,項目名稱:pyt,代碼行數:22,代碼來源:stmt_visitor.py


注:本文中的ast.Assign方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。