本文整理汇总了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
示例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.
示例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())
示例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
示例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
示例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
示例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)]
示例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
示例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
示例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()
示例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()
示例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}
示例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))
示例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())
示例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