本文整理匯總了Python中astunparse.unparse方法的典型用法代碼示例。如果您正苦於以下問題:Python astunparse.unparse方法的具體用法?Python astunparse.unparse怎麽用?Python astunparse.unparse使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類astunparse
的用法示例。
在下文中一共展示了astunparse.unparse方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _get_name_of_callable
# 需要導入模塊: import astunparse [as 別名]
# 或者: from astunparse import unparse [as 別名]
def _get_name_of_callable(cls, c):
if inspect.ismethod(c):
return c.im_class.__name__+'.'+c.__name__
if inspect.isfunction(c):
if c.__name__ == (lambda: None).__name__:
filename = c.func_code.co_filename
cls._ensure_file_in_cache(filename, c)
definitions = cls._LAMBDA_CACHE[filename][c.func_code.co_firstlineno]
assert definitions
# If there's multiple definitions at the same line, there's not enough
# information to distinguish which lambda c refers to, so just let
# python's generic lambda name be used
if len(definitions) == 1:
return astunparse.unparse(definitions[0]).strip()
return c.__name__
if hasattr(c, '__call__'):
return c.__class__.__name__+'.__call__'
return repr(c)
示例2: xproto_fol_to_python_test
# 需要導入模塊: import astunparse [as 別名]
# 或者: from astunparse import unparse [as 別名]
def xproto_fol_to_python_test(policy, fol, model, tag=None):
if isinstance(fol, jinja2.Undefined):
raise Exception("Could not find policy:", policy)
f2p = FOL2Python()
fol_reduced = f2p.hoist_outer(fol)
if fol_reduced in ["True", "False"] and fol != fol_reduced:
raise TrivialPolicy(
"Policy %(name)s trivially reduces to %(reduced)s."
"If this is what you want, replace its contents with %(reduced)s"
% {"name": policy, "reduced": fol_reduced}
)
a = f2p.gen_test_function(fol_reduced, policy, tag="security_check")
return astunparse.unparse(a)
示例3: xproto_fol_to_python_validator
# 需要導入模塊: import astunparse [as 別名]
# 或者: from astunparse import unparse [as 別名]
def xproto_fol_to_python_validator(policy, fol, model, message, tag=None):
if isinstance(fol, jinja2.Undefined):
raise Exception("Could not find policy:", policy)
f2p = FOL2Python()
fol_reduced = f2p.hoist_outer(fol)
if fol_reduced in ["True", "False"] and fol != fol_reduced:
raise TrivialPolicy(
"Policy %(name)s trivially reduces to %(reduced)s."
"If this is what you want, replace its contents with %(reduced)s"
% {"name": policy, "reduced": fol_reduced}
)
a = f2p.gen_validation_function(fol_reduced, policy, message, tag="validator")
return astunparse.unparse(a)
示例4: _process_frame
# 需要導入模塊: import astunparse [as 別名]
# 或者: from astunparse import unparse [as 別名]
def _process_frame(cls, frame, ignore_set, with_vars, additional_varmap=None):
"""This processes a stack frame into an expect_tests.CheckFrame, which
includes file name, line number, function name (of the function containing
the frame), the parsed statement at that line, and the relevant local
variables/subexpressions (if with_vars is True).
In addition to transforming the expression with _checkTransformer, this
will:
* omit subexpressions which resolve to callable()'s
* omit the overall step ordered dictionary
* transform all subexpression values using render_user_value().
"""
nodes = cls._get_statements_for_frame(frame)
raw_frame, filename, lineno, func_name, _, _ = frame
varmap = None
if with_vars:
varmap = dict(additional_varmap or {})
xfrmr = _checkTransformer(raw_frame.f_locals, raw_frame.f_globals)
xfrmd = xfrmr.visit(ast.Module(copy.deepcopy(nodes)))
for n in itertools.chain(ast.walk(xfrmd), xfrmr.extras):
if isinstance(n, _resolved):
val = n.value
if isinstance(val, ast.AST):
continue
if n.representation in ('True', 'False', 'None'):
continue
if callable(val) or id(val) in ignore_set:
continue
if n.representation not in varmap:
varmap[n.representation] = render_user_value(val)
return CheckFrame(
filename,
lineno,
func_name,
'; '.join(astunparse.unparse(n).strip() for n in nodes),
varmap
)
示例5: test_unflattening
# 需要導入模塊: import astunparse [as 別名]
# 或者: from astunparse import unparse [as 別名]
def test_unflattening(self):
'Tests to see if unflattening is correct'
tests = [("x + (3 + y)", "3 + (y + x)"),
("x*(2*z)", "2*(z*x)"),
("x + (y + (z*(5*var)))", "y + (5*(var*z) + x)")]
for test, ref in tests:
ref_ast = ast.parse(ref)
ast_test = ast.parse(test)
Flattening().visit(ast_test)
Unflattening().visit(ast_test)
self.assertTrue(Comparator().visit(ast_test, ref_ast))
self.assertFalse('BoolOp' in astunparse.unparse(ast_test))
示例6: apply_cse
# 需要導入模塊: import astunparse [as 別名]
# 或者: from astunparse import unparse [as 別名]
def apply_cse(expr, outputfile=None):
"""
Apply CSE on expression file or string
"""
if isinstance(expr, str):
if os.path.isfile(expr):
exprfile = open(expr, 'r')
expr_ast = ast.parse(exprfile.read())
else:
expr_ast = ast.parse(expr)
elif isinstance(expr, ast.AST):
if isinstance(expr, ast.Module):
expr_ast = deepcopy(expr)
else:
expr_ast = ast.Expr(expr)
PromoteUnaryOp().visit(expr_ast)
HandleCommutativity().visit(expr_ast)
simple_cse(expr_ast)
expr_ast = PostProcessing().visit(expr_ast)
expr_string = astunparse.unparse(expr_ast).strip('\n')
if outputfile:
output_file = open(outputfile, 'w')
output_file.write(expr_string)
output_file.close()
return expr_string, expr_ast
示例7: simplify
# 需要導入模塊: import astunparse [as 別名]
# 或者: from astunparse import unparse [as 別名]
def simplify(self, expr_ast, nbits):
'Apply pattern matching and arithmetic simplification'
expr_ast = arithm_simpl.run(expr_ast, nbits)
expr_ast = asttools.GetConstMod(self.nbits).visit(expr_ast)
if DEBUG:
print "arithm simpl: "
print unparse(expr_ast)
if DEBUG:
print "before matching: "
print unparse(expr_ast)
expr_ast = all_preprocessings(expr_ast, self.nbits)
# only flattening ADD nodes because of traditionnal MBA patterns
expr_ast = Flattening(ast.Add).visit(expr_ast)
for pattern, repl in self.patterns:
rep = pattern_matcher.PatternReplacement(pattern, expr_ast, repl)
new_ast = rep.visit(deepcopy(expr_ast))
if not asttools.Comparator().visit(new_ast, expr_ast):
if DEBUG:
print "replaced! "
dispat = deepcopy(pattern)
dispat = Unflattening().visit(dispat)
print "pattern: ", unparse(dispat)
disnew = deepcopy(new_ast)
disnew = Unflattening().visit(disnew)
print "after: ", unparse(disnew)
print ""
expr_ast = new_ast
break
# bitwise simplification: this is a ugly hack, should be
# "generalized"
expr_ast = Flattening(ast.BitXor).visit(expr_ast)
expr_ast = asttools.ConstFolding(expr_ast, self.nbits).visit(expr_ast)
expr_ast = Unflattening().visit(expr_ast)
if DEBUG:
print "after PM: "
print unparse(expr_ast)
return expr_ast
示例8: loop_simplify
# 需要導入模塊: import astunparse [as 別名]
# 或者: from astunparse import unparse [as 別名]
def loop_simplify(self, node):
'Simplifying loop to reach fixpoint'
old_value = deepcopy(node.value)
old_value = Flattening().visit(old_value)
node.value = self.simplify(node.value, self.nbits)
copyvalue = deepcopy(node.value)
copyvalue = Flattening().visit(copyvalue)
# simplify until fixpoint is reached
while not asttools.Comparator().visit(old_value, copyvalue):
old_value = deepcopy(node.value)
node.value = self.simplify(node.value, self.nbits)
copyvalue = deepcopy(node.value)
if len(unparse(copyvalue)) > len(unparse(old_value)):
node.value = deepcopy(old_value)
break
copyvalue = Flattening().visit(copyvalue)
old_value = Flattening().visit(old_value)
if asttools.Comparator().visit(old_value, copyvalue):
old_value = deepcopy(node.value)
node.value = NotToInv().visit(node.value)
node.value = self.simplify(node.value, self.nbits)
copyvalue = deepcopy(node.value)
# discard if NotToInv increased the size
if len(unparse(copyvalue)) >= len(unparse(old_value)):
node.value = deepcopy(old_value)
copyvalue = deepcopy(node.value)
copyvalue = Flattening().visit(copyvalue)
old_value = Flattening().visit(old_value)
if DEBUG:
print "-"*80
# final arithmetic simplification to clean output of matching
node.value = arithm_simpl.run(node.value, self.nbits)
asttools.GetConstMod(self.nbits).visit(node.value)
if DEBUG:
print "arithm simpl: "
print unparse(node.value)
print ""
print "-"*80
return node
示例9: test_unparse
# 需要導入模塊: import astunparse [as 別名]
# 或者: from astunparse import unparse [as 別名]
def test_unparse(self):
for src_py in self.srcs:
with open(src_py) as f:
content = f.read()
gnode = gast.parse(content)
astunparse.unparse(gast.gast_to_ast(gnode))
示例10: json_to_string
# 需要導入模塊: import astunparse [as 別名]
# 或者: from astunparse import unparse [as 別名]
def json_to_string(schema: JSON_TYPE) -> str:
s1 = json.dumps(schema)
s2 = ast.parse(s1)
s3 = astunparse.unparse(s2).strip()
s4 = re.sub(r'}, {\n (\s+)', r'},\n\1{ ', s3)
s5 = re.sub(r'\[{\n (\s+)', r'[\n\1{ ', s4)
s6 = re.sub(r"'\$schema':[^\n{}\[\]]+\n\s+", "\1", s5)
while True:
s7 = re.sub(r',\n\s*([\]}])', r'\1', s6)
if s6 == s7:
break
s6 = s7
s8 = re.sub(r'{\s+}', r'{}', s7)
return s8
示例11: process_signature
# 需要導入模塊: import astunparse [as 別名]
# 或者: from astunparse import unparse [as 別名]
def process_signature(*args: Any) -> Optional[Tuple[str, str]]:
"""Strip type hints from signatures."""
signature = args[5]
if signature is None:
return None
assert isinstance(signature, str)
node = ast.parse(f'def f{signature}: pass').body[0]
assert isinstance(node, ast.FunctionDef)
node.returns = None
if node.args.args:
for arg in node.args.args:
arg.annotation = None
return astunparse.unparse(node).splitlines()[2][5:-1], ''
示例12: unparse
# 需要導入模塊: import astunparse [as 別名]
# 或者: from astunparse import unparse [as 別名]
def unparse(node, strip=None):
result = astunparse.unparse(node)
if strip:
result = result.lstrip().rstrip()
if isinstance(node, _ast.BinOp):
return result[1:-1]
return result
示例13: parse_function
# 需要導入模塊: import astunparse [as 別名]
# 或者: from astunparse import unparse [as 別名]
def parse_function(node):
old_style = None
new_style = None
output = None
setup = []
setup_done = False
title, details = parse_docstring(ast.get_docstring(node, clean=True))
name = node.name[5:] if node.name.startswith('test_') else node.name
for n in node.body:
# Ignore the docstring
if isinstance(n, _ast.Expr) and isinstance(n.value, _ast.Str):
continue
if isinstance(n, _ast.Assign) and n.targets[0].id == 'old_result':
setup_done = True
old_style = unparse(n.value, strip=True)
if isinstance(n, _ast.Assign) and n.targets[0].id == 'new_result':
setup_done = True
new_style = unparse(n.value, strip=True)
if isinstance(n, _ast.Assert) and isinstance(
n.test.comparators[0], _ast.Str):
setup_done = True
output = n.test.comparators[0].s
if not setup_done:
setup.append(n)
if setup:
setup = unparse(setup, strip=True)
return Example(
name,
title,
details,
setup or "",
old_style or "",
new_style or "",
output or ""
)
示例14: save
# 需要導入模塊: import astunparse [as 別名]
# 或者: from astunparse import unparse [as 別名]
def save(self):
code = astunparse.unparse(self._node)
with open(self._schema['file']) as f:
f.write(code)
示例15: ast2py
# 需要導入模塊: import astunparse [as 別名]
# 或者: from astunparse import unparse [as 別名]
def ast2py(ast, mochi_env='', add_init=False):
"""Translate Python AST to Python code.
:param ast: Python AST
:param env: Mochi environment such monkey patch
:param add_init: Add Mochi intialization or not
:return: Python source code
"""
if mochi_env:
env_ast = translator.translate_block(mochi_env)
ast.body = env_ast.body + ast.body
source = astunparse.unparse(ast)
if add_init:
source = INIT_CODE + source
return source