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


Python ast.Dict方法代码示例

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


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

示例1: _apply_imports_to_unparsed_expression

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Dict [as 别名]
def _apply_imports_to_unparsed_expression(exp_ast, imports):
  """Attempts to evaluate the code equivalent of `exp_ast`, with `imports`
  as available symbols. If it's successful, it returns the evaluated object.
  Otherwise this returns the unparsed code for `exp_ast`.

  Args:
    * exp_ast (Union[ast.Name, ast.Attribute, ast.Call]) - The expression to
      evaluate.
    * imports (Dict[str, object]) - The symbols to include during the evaluation
      of `exp_ast`.

  Returns the evaluation of `exp_ast` if it can successfully evaluate with
  `imports`. Otherwise this returns the source-code representation of exp_ast as
  a string.
  """
  assert isinstance(exp_ast, (ast.Name, ast.Attribute, ast.Call)), type(exp_ast)
  unparsed = _unparse(exp_ast).strip()
  try:
    return eval(unparsed, {'__builtins__': None}, imports)
  except (NameError, AttributeError):
    return unparsed 
开发者ID:luci,项目名称:recipes-py,代码行数:23,代码来源:cmd.py

示例2: get_value

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Dict [as 别名]
def get_value(self, node):
        """Convert value from an AST node."""
        if not isinstance(node, ast.Dict):
            raise TypeError("must be a dictionary")

        evaluator = SafeEvaluator()
        try:
            value = evaluator.run(node)
        except Exception as ex:
            # TODO: Handle errors.
            raise ex

        try:
            # Ensure value is a serializable dictionary.
            value = json.loads(json.dumps(value))
            if not isinstance(value, dict):
                raise TypeError
        except (TypeError, ValueError):
            raise TypeError("must be serializable")

        return value


# Possible process metadata. 
开发者ID:genialis,项目名称:resolwe,代码行数:26,代码来源:parser.py

示例3: pop_format_context

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Dict [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

示例4: read_from_directory

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Dict [as 别名]
def read_from_directory(
        cls, directory
    ):  # type: (Union[basestring, Path]) -> Dict[str, Union[List, Dict]]
        if isinstance(directory, basestring):
            directory = Path(directory)

        result = cls.DEFAULT.copy()
        for filename in cls.FILES:
            filepath = directory / filename
            if not filepath.exists():
                continue

            new_result = getattr(cls(), "read_{}".format(filename.replace(".", "_")))(
                filepath
            )

            for key in result.keys():
                if new_result[key]:
                    result[key] = new_result[key]

        return result 
开发者ID:python-poetry,项目名称:poetry,代码行数:23,代码来源:setup_reader.py

示例5: __init__

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Dict [as 别名]
def __init__(self,
                 symbol_table: SymbolTable,
                 custom_types_symbol_table: SymbolTable,
                 external_ir2_symbols_by_name_by_module: Dict[str, Dict[str, Union[ir2.FunctionDefn, ir2.CustomType]]],
                 filename: str,
                 source_lines: List[str],
                 identifier_generator: Iterator[str],
                 function_name: Optional[str] = None,
                 function_definition_line: Optional[int] = None,
                 first_enclosing_except_stmt_line: Optional[int] = None,
                 partially_typechecked_function_definitions_by_name: Dict[str, ast.FunctionDef] = None):
        assert (function_name is None) == (function_definition_line is None)
        self.symbol_table = symbol_table
        self.custom_types_symbol_table = custom_types_symbol_table
        self.external_ir2_symbols_by_name_by_module = external_ir2_symbols_by_name_by_module
        self.partially_typechecked_function_definitions_by_name = partially_typechecked_function_definitions_by_name or dict()
        self.filename = filename
        self.source_lines = source_lines
        self.current_function_name = function_name
        self.current_function_definition_line = function_definition_line
        self.first_enclosing_except_stmt_line = first_enclosing_except_stmt_line
        self.identifier_generator = identifier_generator 
开发者ID:google,项目名称:tmppy,代码行数:24,代码来源:_ast_to_ir2.py

示例6: read_from_directory

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Dict [as 别名]
def read_from_directory(
        cls, directory
    ):  # type: (Union[str, Path]) -> Dict[str, Union[List, Dict]]
        if isinstance(directory, str):
            directory = Path(directory)

        result = cls.DEFAULT.copy()
        for filename in cls.FILES:
            filepath = directory / filename
            if not filepath.exists():
                continue

            new_result = getattr(cls(), "read_{}".format(filename.replace(".", "_")))(
                filepath
            )

            for key in result.keys():
                if new_result[key]:
                    result[key] = new_result[key]

        return result 
开发者ID:frostming,项目名称:pdm,代码行数:23,代码来源:readers.py

示例7: _replace_typed_class

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Dict [as 别名]
def _replace_typed_class(
        tokens: List[Token],
        i: int,
        call: ast.Call,
        types: Dict[str, ast.expr],
) -> None:
    if i > 0 and tokens[i - 1].name in {'INDENT', UNIMPORTANT_WS}:
        indent = f'{tokens[i - 1].src}{" " * 4}'
    else:
        indent = ' ' * 4

    # NT = NamedTuple("nt", [("a", int)])
    # ^i                                 ^end
    end = i + 1
    while end < len(tokens) and tokens[end].name != 'NEWLINE':
        end += 1

    attrs = '\n'.join(f'{indent}{k}: {_unparse(v)}' for k, v in types.items())
    src = f'class {tokens[i].src}({_unparse(call.func)}):\n{attrs}'
    tokens[i:end] = [Token('CODE', src)] 
开发者ID:asottile,项目名称:pyupgrade,代码行数:22,代码来源:pyupgrade.py

示例8: parse_setup_function

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Dict [as 别名]
def parse_setup_function(self):
        setup = {}  # type: Dict[Any, Any]
        self.unmap_binops()
        function_names = self.parse_functions()
        if "setup" in function_names:
            setup = self.unparse(function_names["setup"])
        keys = list(setup.keys())
        if len(keys) == 1 and keys[0] is None:
            _, setup = setup.popitem()
        keys = list(setup.keys())
        for k in keys:
            # XXX: Remove unresolved functions from the setup dictionary
            if isinstance(setup[k], dict):
                if not setup[k]:
                    continue
                key = next(iter(setup[k].keys()))
                val = setup[k][key]
                if key in function_names and val is None or val == {}:
                    setup.pop(k)
        return setup 
开发者ID:pypa,项目名称:pipenv,代码行数:22,代码来源:setup_info.py

示例9: ast_parse_setup_py

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Dict [as 别名]
def ast_parse_setup_py(path):
    # type: (S) -> Dict[Any, Any]
    ast_analyzer = ast_parse_file(path)
    setup = {}  # type: Dict[Any, Any]
    ast_analyzer.unmap_binops()
    function_names = ast_analyzer.parse_functions()
    if "setup" in function_names:
        setup = ast_unparse(function_names["setup"], analyzer=ast_analyzer)
    keys = list(setup.keys())
    if len(keys) == 1 and keys[0] is None:
        _, setup = setup.popitem()
    keys = list(setup.keys())
    for k in keys:
        # XXX: Remove unresolved functions from the setup dictionary
        if isinstance(setup[k], dict):
            if not setup[k]:
                continue
            key = next(iter(setup[k].keys()))
            val = setup[k][key]
            if key in function_names and val is None or val == {}:
                setup.pop(k)
    return setup 
开发者ID:pypa,项目名称:pipenv,代码行数:24,代码来源:setup_info.py

示例10: get_initial_info

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Dict [as 别名]
def get_initial_info(self):
        # type: () -> Dict[S, Any]
        parse_setupcfg = False
        parse_setuppy = False
        if self.setup_cfg and self.setup_cfg.exists():
            parse_setupcfg = True
        if self.setup_py and self.setup_py.exists():
            parse_setuppy = True
        if parse_setuppy or parse_setupcfg:
            with cd(self.base_dir):
                if parse_setuppy:
                    self.update_from_dict(self.parse_setup_py())
                if parse_setupcfg:
                    self.update_from_dict(self.parse_setup_cfg())
            if self.name is not None and any(
                [
                    self.requires,
                    self.setup_requires,
                    self._extras_requirements,
                    self.build_backend,
                ]
            ):
                return self.as_dict()
        return self.get_info() 
开发者ID:pypa,项目名称:pipenv,代码行数:26,代码来源:setup_info.py

示例11: get_info

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Dict [as 别名]
def get_info(self):
        # type: () -> Dict[S, Any]
        with cd(self.base_dir):
            self.run_pyproject()
            self.build()

        if self.setup_py and self.setup_py.exists() and self.metadata is None:
            if not self.requires or not self.name:
                try:
                    with cd(self.base_dir):
                        self.run_setup()
                except Exception:
                    with cd(self.base_dir):
                        metadata = self.get_egg_metadata()
                        if metadata:
                            self.populate_metadata(metadata)
                if self.metadata is None or not self.name:
                    with cd(self.base_dir):
                        metadata = self.get_egg_metadata()
                        if metadata:
                            self.populate_metadata(metadata)

        return self.as_dict() 
开发者ID:pypa,项目名称:pipenv,代码行数:25,代码来源:setup_info.py

示例12: as_dict

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Dict [as 别名]
def as_dict(self):
        # type: () -> Dict[STRING_TYPE, Any]
        prop_dict = {
            "name": self.name,
            "version": self.version if self._version else None,
            "base_dir": self.base_dir,
            "ireq": self.ireq,
            "build_backend": self.build_backend,
            "build_requires": self.build_requires,
            "requires": self.requires if self._requirements else None,
            "setup_requires": self.setup_requires,
            "python_requires": self.python_requires,
            "extras": self.extras if self._extras_requirements else None,
            "extra_kwargs": self.extra_kwargs,
            "setup_cfg": self.setup_cfg,
            "setup_py": self.setup_py,
            "pyproject": self.pyproject,
        }
        return {k: v for k, v in prop_dict.items() if v} 
开发者ID:pypa,项目名称:pipenv,代码行数:21,代码来源:setup_info.py

示例13: CheckNode

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Dict [as 别名]
def CheckNode(node, keypath):
  if isinstance(node, ast.Dict):
    dict = {}
    for key, value in zip(node.keys, node.values):
      assert isinstance(key, ast.Str)
      key = key.s
      if key in dict:
        raise GypError("Key '" + key + "' repeated at level " + repr(len(keypath) + 1) + " with key path '" + '.'.join(keypath) + "'")
      kp = list(keypath)  # Make a copy of the list for descending this node.
      kp.append(key)
      dict[key] = CheckNode(value, kp)
    return dict
  elif isinstance(node, ast.List):
    children = []
    for index, child in enumerate(node.elts):
      kp = list(keypath)  # Copy list.
      kp.append(repr(index))
      children.append(CheckNode(child, kp))
    return children
  elif isinstance(node, ast.Str):
    return node.s
  elif isinstance(node, ast.Num):
    return node.n
  else:
    raise TypeError("Unknown AST node at key path '" + '.'.join(keypath) + "': " + repr(node)) 
开发者ID:refack,项目名称:GYP3,代码行数:27,代码来源:input.py

示例14: pop_format_context

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Dict [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

示例15: transform2call

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Dict [as 别名]
def transform2call(var):
    if isinstance(var, ast.BinOp):
        is_mod = isinstance(var.op, ast.Mod)
        is_left_str = isinstance(var.left, ast.Str)
        if is_mod and is_left_str:
            new_call = ast.Call()
            new_call.args = []
            new_call.args = []
            if six.PY2:
                new_call.starargs = None
            new_call.keywords = None
            if six.PY2:
                new_call.kwargs = None
            new_call.lineno = var.lineno
            new_call.func = ast.Attribute()
            new_call.func.value = var.left
            new_call.func.attr = 'format'
            if isinstance(var.right, ast.Tuple):
                new_call.args = var.right.elts
            elif six.PY2 and isinstance(var.right, ast.Dict):
                new_call.kwargs = var.right
            else:
                new_call.args = [var.right]
            return new_call 
开发者ID:PyCQA,项目名称:bandit,代码行数:26,代码来源:django_xss.py


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