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