當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。