Python ast.Module方法代碼示例- 純淨天空
文章推薦指數: 80 %
Python ast. ... 如果您正苦於以下問題:Python ast. ... 需要導入模塊: import ast [as 別名] # 或者: from ast import Module [as 別名] def ast(self) -> ast.
當前位置:首頁>>代碼示例>>Python>>正文
本文整理匯總了Python中ast.Module方法的典型用法代碼示例。
如果您正苦於以下問題:Pythonast.Module方法的具體用法?Pythonast.Module怎麽用?Pythonast.Module使用的例子?那麽恭喜您,這裏精選的方法代碼示例或許可以為您提供幫助。
您也可以進一步了解該方法所在類ast的用法示例。
在下文中一共展示了ast.Module方法的20個代碼示例,這些例子默認根據受歡迎程度排序。
您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的Python代碼示例。
示例1:ast
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportModule[as別名]
defast(self)->ast.Module:#type:ignore
"""AbstractSyntaxTree(AST)representationofthesource_file.
Thisiscachedlocallyandupdatedifthesource_fileischanged.
Returns:
ParsedASTforthesourcefile.
Raises:
TypeError:if``source_file``isnotset.
"""
ifself._astisNone:
ifnotself.source_file:
raiseTypeError("Source_filepropertyissettoNoneType.")
withopen(self.source_file,"rb")assrc_stream:
self._ast=ast.parse(src_stream.read())
returnself._ast開發者ID:EvanKepner,項目名稱:mutatest,代碼行數:20,代碼來源:api.py
示例2:generic_visit
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportModule[as別名]
defgeneric_visit(self,node):
#Fallbackwhenwedon'thaveaspecialimplementation.
if_is_ast_expr(node):
mod=ast.Expression(node)
co=self._compile(mod)
try:
result=self.frame.eval(co)
exceptException:
raiseFailure()
explanation=self.frame.repr(result)
returnexplanation,result
elif_is_ast_stmt(node):
mod=ast.Module([node])
co=self._compile(mod,"exec")
try:
self.frame.exec_(co)
exceptException:
raiseFailure()
returnNone,None
else:
raiseAssertionError("can'thandle%s"%(node,))開發者ID:pytest-dev,項目名稱:py,代碼行數:23,代碼來源:_assertionnew.py
示例3:__init__
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportModule[as別名]
def__init__(self,patt_ast,target_ast,rep_ast,nbits=0):
'Patternastshouldhaveasroot:BinOp,BoolOp,UnaryOporCall'
ifisinstance(patt_ast,ast.Module):
self.patt_ast=patt_ast.body[0].value
elifisinstance(patt_ast,ast.Expression):
self.patt_ast=patt_ast.body
else:
self.patt_ast=patt_ast
ifisinstance(rep_ast,ast.Module):
self.rep_ast=deepcopy(rep_ast.body[0].value)
elifisinstance(rep_ast,ast.Expression):
self.rep_ast=deepcopy(rep_ast.body)
else:
self.rep_ast=deepcopy(rep_ast)
ifnotnbits:
getsize=asttools.GetSize()
getsize.visit(target_ast)
ifgetsize.result:
self.nbits=getsize.result
#defaultbitsizeis8
else:
self.nbits=8
else:
self.nbits=nbits開發者ID:quarkslab,項目名稱:sspam,代碼行數:27,代碼來源:pattern_matcher.py
示例4:test_dump
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportModule[as別名]
deftest_dump(self):
node=ast.parse('spam(eggs,"andcheese")')
self.assertEqual(ast.dump(node),
"Module(body=[Expr(value=Call(func=Name(id='spam',ctx=Load()),"
"args=[Name(id='eggs',ctx=Load()),Str(s='andcheese')],"
"keywords=[],starargs=None,kwargs=None))])"
)
self.assertEqual(ast.dump(node,annotate_fields=False),
"Module([Expr(Call(Name('spam',Load()),[Name('eggs',Load()),"
"Str('andcheese')],[],None,None))])"
)
self.assertEqual(ast.dump(node,include_attributes=True),
"Module(body=[Expr(value=Call(func=Name(id='spam',ctx=Load(),"
"lineno=1,col_offset=0),args=[Name(id='eggs',ctx=Load(),"
"lineno=1,col_offset=5),Str(s='andcheese',lineno=1,"
"col_offset=11)],keywords=[],starargs=None,kwargs=None,"
"lineno=1,col_offset=0),lineno=1,col_offset=0)])"
)開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:20,代碼來源:test_ast.py
示例5:test_topython_generates_code_for_alt
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportModule[as別名]
deftest_topython_generates_code_for_alt(self):
alt=parsing.Alt(
ParseTreeStub('a',False),ParseTreeStub('b',False))
res=codegen.to_source(ast.Module(passes.rule_topython(alt)))
self.assertEqual(res,("try:\n"
"try:\n"
"if(nota):\n"
"raiseAltFalse()\n"
"raiseAltTrue()\n"
"exceptAltFalse:\n"
"pass\n"
"try:\n"
"if(notb):\n"
"raiseAltFalse()\n"
"raiseAltTrue()\n"
"exceptAltFalse:\n"
"pass\n"
"returnFalse\n"
"exceptAltTrue:\n"
"pass"))開發者ID:LionelAuroux,項目名稱:pyrser,代碼行數:22,代碼來源:test_topython.py
示例6:new_functionCFG
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportModule[as別名]
defnew_functionCFG(self,node,asynchr=False):
"""
Createanewsub-CFGforafunctiondefinitionandaddittothe
functionCFGsoftheCFGbeingbuilt.
Args:
node:TheASTnodecontainingthefunctiondefinition.
async:BooleanindicatingwhetherthefunctionforwhichtheCFGis
beingbuiltisasynchronousornot.
"""
self.current_id+=1
#Anewsub-CFGiscreatedforthebodyofthefunctiondefinitionand
#addedtothefunctionCFGsofthecurrentCFG.
func_body=ast.Module(body=node.body)
func_builder=CFGBuilder()
self.cfg.functioncfgs[node.name]=func_builder.build(node.name,
func_body,
asynchr,
self.current_id)
self.current_id=func_builder.current_id+1開發者ID:coetaur0,項目名稱:staticfg,代碼行數:22,代碼來源:builder.py
示例7:transform_ast
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportModule[as別名]
deftransform_ast(self,node):
"""ApplytheASTtransformationsfromself.ast_transformers
Parameters
----------
node:ast.Node
Therootnodetobetransformed.Typicallycalledwiththeast.Module
producedbyparsinguserinput.
Returns
-------
Anast.Nodecorrespondingtothenodeitwascalledwith.Notethatit
mayalsomodifythepassedobject,sodon'trelyonreferencestothe
originalAST.
"""
fortransformerinself.ast_transformers:
try:
node=transformer.visit(node)
exceptException:
warn("ASTtransformer%rthrewanerror.Itwillbeunregistered."%transformer)
self.ast_transformers.remove(transformer)
ifself.ast_transformers:
ast.fix_missing_locations(node)
returnnode開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:27,代碼來源:interactiveshell.py
示例8:find_func
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportModule[as別名]
deffind_func(module,namespace):
"""Filterawayeverythingexceptthefunction
Addionallyrenamethefunctionforbetterreadability.
Args:
module(ast.Module):theentireparsedcode
namespace(str):identifierforthefunctionofinterest
`namspace`willbeoftheform,'some_var')->ast.Num(100)
Args:
*mod_ast(ast.Module)-TheparsedPythonmodulecode.
*target(str)-Thevariablenametolookforanassignmentto.
ReturnsthePythonASTobjectwhichistheright-hand-sideofanassignmentto
`target`.
"""
assertisinstance(mod_ast,ast.Module),type(mod_ast)
fornodeinmod_ast.body:
ifisinstance(node,ast.Assign):
if(len(node.targets)==1and
isinstance(node.targets[0],ast.Name)and
node.targets[0].id==target):
returnnode.value,node.lineno
returnNone,None開發者ID:luci,項目名稱:recipes-py,代碼行數:28,代碼來源:cmd.py
示例15:parse_deps
點讚5
#需要導入模塊:importast[as別名]
#或者:fromastimportModule[as別名]
defparse_deps(repo_name,mod_ast,relpath):
"""Findsandparsesthe`DEPS`variableoutof`mod_ast`.
Args:
*repo_name(str)-Theimplicitrepo_nameforDEPSentrieswhichdonot
specifyone.
*mod_ast(ast.Module)-ThePythonmoduleASTtoparsefrom.
*relpath(str)-Theposix-stylerelativepathwhichshouldbeassociated
withthecodeinclass_ast.
ReturnsDoc.Depsprotomesssage.
"""
assertisinstance(mod_ast,ast.Module),type(mod_ast)
ret=None
DEPS,lineno=_find_value_of(mod_ast,'DEPS')
ifDEPS:
ret=doc.Doc.Deps(
relpath=relpath,
lineno=lineno,
)
spec=parse_deps_spec(repo_name,ast.literal_eval(_unparse(DEPS)))
fordep_repo_name,mod_nameinsorted(spec.itervalues()):
ret.module_links.add(repo_name=dep_repo_name,name=mod_name)
returnret開發者ID:luci,項目名稱:recipes-py,代碼行數:28,代碼來源:cmd.py
示例16:parse_parameters
點讚5
#需要導入模塊:importast[as別名]
#或者:fromastimportModule[as別名]
defparse_parameters(mod_ast,relpath):
"""ParsesasetofrecipeparametersfromthePROPERTIESvariable.
Args:
*mod_ast(ast.Module)-TheparsedPythonmodulecode.
*relpath(str)-Theposix-stylerelativepathwhichshouldbeassociated
withthecodeinmod_ast.
ReturnsDoc.Parameters.
"""
assertisinstance(mod_ast,ast.Module),type(mod_ast)
parameters,lineno=_find_value_of(mod_ast,'PROPERTIES')
ifnotparameters:
returnNone
ifnotisinstance(parameters,ast.Dict):
#TODO(iannucci):Docsfornew-styleProtobufPROPERTIES.
returnNone
imports=_parse_mock_imports(mod_ast,MOCK_IMPORTS_PARAMETERS)
imports.update(extract_jsonish_assignments(mod_ast))
data=eval(_unparse(parameters),imports)
ifnotdata:
returnNone
fork,vinsorted(data.iteritems()):
data[k]=parse_parameter(v)
returndoc.Doc.Parameters(relpath=relpath,lineno=lineno,parameters=data)開發者ID:luci,項目名稱:recipes-py,代碼行數:31,代碼來源:cmd.py
示例17:visit_Assign
點讚5
#需要導入模塊:importast[as別名]
#或者:fromastimportModule[as別名]
defvisit_Assign(self,assign):
value_explanation,value_result=self.visit(assign.value)
explanation="...=%s"%(value_explanation,)
name=ast.Name("__exprinfo_expr",ast.Load(),
lineno=assign.value.lineno,
col_offset=assign.value.col_offset)
new_assign=ast.Assign(assign.targets,name,lineno=assign.lineno,
col_offset=assign.col_offset)
mod=ast.Module([new_assign])
co=self._compile(mod,"exec")
try:
self.frame.exec_(co,__exprinfo_expr=value_result)
exceptException:
raiseFailure(explanation)
returnexplanation,value_result開發者ID:pytest-dev,項目名稱:py,代碼行數:17,代碼來源:_assertionnew.py
示例18:test_compile_to_ast
點讚5
#需要導入模塊:importast[as別名]
#或者:fromastimportModule[as別名]
deftest_compile_to_ast(self):
importast
source=Source("x=4")
mod=source.compile(flag=ast.PyCF_ONLY_AST)
assertisinstance(mod,ast.Module)
compile(mod,"
延伸文章資訊
- 1Python 函式eval 與ast.literal_eval 的區別
主題: Python. 一分鐘學個小知識. eval 與 ast.literal_eval 都可以將字串還原成它能夠轉化成的資料型別,例如 >>> from ast import literal...
- 2Python Ast介紹及應用- IT閱讀
Ast是python原始碼到位元組碼的一種中間產物,藉助ast模組可以從語法樹的角度分析原始碼結構。此外,我們不僅可以修改和執行語法樹,還可以將Source生成的 ...
- 3AST 模块:用Python 修改Python 代码 - PyCoder's Weekly ...
Python 从2.6 开始就提供了现在这样的 ast 模块,它提供了一种访问和修改AST 的简单方式。 通过这个,我们可以从AST 中生成代码对象,也可以出于某些原因,根据修改过的AST ...
- 4ast --- 抽象语法树— Python 3.8.13 說明文件
ast 模块帮助Python 程序处理Python 语法的抽象语法树。抽象语法或许会随着Python 的更新发布而改变;该模块能够帮助理解当前语法在编程层面的样貌。
- 5Python Ast介绍及应用 - 博客园
Ast是python源码到字节码的一种中间产物,借助ast模块可以从语法树的角度分析源码结构。此外,我们不仅可以修改和执行语法树,还可以将Source生成的语法树 ...