Python ast.Module方法代碼示例- 純淨天空

文章推薦指數: 80 %
投票人數:10人

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. Returns: module(ast.Module):theoriginalmodulebutwitheverythingfiltered awayexceptthefunctionandthefunctionwithamorereadablename """ module_name,func_name=namespace.split('.') funcs=[stmtforstmtinmodule.bodyifisinstance(stmt,ast.FunctionDef)] func,=[funcforfuncinfuncsiffunc.name==func_name] func.name=f'{module_name}.{func_name}' module.body=[func] returnmodule開發者ID:ebanner,項目名稱:pynt,代碼行數:24,代碼來源:syntax.py 示例9:find_method ​點讚6 ​ #需要導入模塊:importast[as別名] #或者:fromastimportModule[as別名] deffind_method(module,namespace): """Filterawayeverythingexceptthemethod Promotethemethoduptotheglobalnamespacesothatitis indistinguishablefromaregularfunction. Arguments: module(ast.Module):theentireparsedsourcecode namespace(str):identifierforthemethodofinterest Returns: module(ast.Module):theoriginalmodulebutwitheverythingfiltered awayexceptthemethodnamebutwiththename`namespace`andpromoted totheglobal(i.e.top)level """ module_name,class_name,method_name=namespace.split('.') classdefs=[stmtforstmtinmodule.bodyifisinstance(stmt,ast.ClassDef)] classdef,=[classdefforclassdefinclassdefsifclassdef.name==class_name] methods=[stmtforstmtinclassdef.bodyifisinstance(stmt,ast.FunctionDef)] formethodinmethods: ifmethod.name==method_name: method.name=f'{module_name}.{class_name}.{method_name}' module.body=[method] returnmodule開發者ID:ebanner,項目名稱:pynt,代碼行數:27,代碼來源:syntax.py 示例10:CheckedEval ​點讚6 ​ #需要導入模塊:importast[as別名] #或者:fromastimportModule[as別名] defCheckedEval(file_contents): """Returntheevalofagypfile. Thegypfileisrestrictedtodictionariesandlistsonly,and repeatedkeysarenotallowed. Notethatthisisslowerthaneval()is. """ syntax_tree=ast.parse(file_contents) assertisinstance(syntax_tree,ast.Module) c1=syntax_tree.body assertlen(c1)==1 c2=c1[0] assertisinstance(c2,ast.Expr) returnCheckNode(c2.value,[])開發者ID:refack,項目名稱:GYP3,代碼行數:18,代碼來源:input.py 示例11:test_progn_uses_custom_eval_fn ​點讚6 ​ #需要導入模塊:importast[as別名] #或者:fromastimportModule[as別名] deftest_progn_uses_custom_eval_fn(self): """ Assertthattheprognfunctionusescustomevalfunctionsproperly. """ eval_fn=mock.MagicMock() try: progn('2+2',eval_fn=eval_fn) exceptQdbPrognEndsInStatement: #Thisistheerrorthatwearegettingbecauseourevalfunction #isnotstoringanyresults. pass calls=eval_fn.call_args_list self.assertEqual(len(calls),1) call_args=calls[0][0] #Thisisconstructedinsidethefunction,butshouldbeamodule. self.assertIsInstance(call_args[0],ast.Module) self.assertEqual(call_args[1],sys._getframe()) self.assertEqual(call_args[2],'exec')開發者ID:quantopian,項目名稱:qdb,代碼行數:24,代碼來源:test_misc.py 示例12:from_ast ​點讚6 ​ #需要導入模塊:importast[as別名] #或者:fromastimportModule[as別名] deffrom_ast(cls,tree:ast.Module)->List['Func']: funcs=[] forexprintree.body: ifnotisinstance(expr,ast.FunctionDef): continue contracts=[] forcategory,argsinget_contracts(expr.decorator_list): contract=Contract( args=args, category=Category(category), func_args=expr.args, ) contracts.append(contract) funcs.append(cls( name=expr.name, args=expr.args, body=expr.body, contracts=contracts, line=expr.lineno, col=expr.col_offset, )) returnfuncs開發者ID:life4,項目名稱:deal,代碼行數:24,代碼來源:_func.py 示例13:__init__ ​點讚5 ​ #需要導入模塊:importast[as別名] #或者:fromastimportModule[as別名] def__init__( self, source_file:Optional[Union[str,Path]]=None, coverage_file:Optional[Union[str,Path]]=Path(".coverage"), filter_codes:Optional[Iterable[str]]=None, )->None: """InitializetheGenome. Thereareinternalpropertiesprefixedwithanunderscoreusedforthelazyevaluation oftheASTandmutationtargets. Args: source_file:anoptionalsourcefilepath coverage_file:coveragefileforfilteringcoveredlines, defaultvalueissetto".coverage". filter_codes:2-lettercategorycodestofilterreturnedtargets """ #Propertieswithanunderscoreprefixareusedforlocalcachingandarenotdesigned #tobemodifieddirectly. #Relatedtosourcefiles,AST,targets self._source_file=None self._ast:Optional[ast.Module]=None self._targets:Optional[Set[LocIndex]]=None #Relatedtocoveragefiltering self._coverage_file=None self._covered_targets:Optional[Set[LocIndex]]=None #Relatedtocategorycodefiltering,notcachedbutusesasetterforvalidvaluechecks self._filter_codes:Set[str]=set() #Initializesetvaluesusingproperties #Thesemaybesetlaterandclearthecachedvaluesinthesetters self.source_file=Path(source_file)ifsource_fileelseNone self.coverage_file=Path(coverage_file)ifcoverage_fileelseNone self.filter_codes:Set[str]=set(filter_codes)iffilter_codeselseset() ################################################################################################ #CATEGORYFILTERCODESPROPERTIES ################################################################################################開發者ID:EvanKepner,項目名稱:mutatest,代碼行數:42,代碼來源:api.py 示例14:_find_value_of ​點讚5 ​ #需要導入模塊:importast[as別名] #或者:fromastimportModule[as別名] def_find_value_of(mod_ast,target): """Looksforanassignmentto`target`,returningtheassignmentvalueAST nodeandthelinenumberoftheassignment. Example: some_var=100 other=20+10 _find_value_of(,'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,"","exec")開發者ID:pytest-dev,項目名稱:py,代碼行數:8,代碼來源:test_source.py 示例19:is_nonglobal_item ​點讚5 ​ #需要導入模塊:importast[as別名] #或者:fromastimportModule[as別名] defis_nonglobal_item(node,max_indentation_depth): current_item=node #preventstheuserfrommakingthisloopexcessivelylong for_inrange(max_indentation_depth): if( nothasattr(current_item,'parent')or isinstance(current_item.parent,ast.Module) ): break ifnotisinstance(current_item.parent,(ast.ClassDef,ast.Assign,ast.If)): returnTrue current_item=current_item.parent returnFalse開發者ID:devmanorg,項目名稱:fiasko_bro,代碼行數:15,代碼來源:ast_helpers.py 示例20:global_context ​點讚5 ​ #需要導入模塊:importast[as別名] #或者:fromastimportModule[as別名] defglobal_context(): returnSymTable( requires=set(), entered=set(), explicit_globals=set(), explicit_nonlocals=set(), parent=None, children=[], depth=0, analyzed=None, cts={ContextType.Module}, )開發者ID:Xython,項目名稱:YAPyPy,代碼行數:14,代碼來源:symbol_analyzer.py 注:本文中的ast.Module方法示例整理自Github/MSDocs等源碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。



請為這篇文章評分?