fst.astutil
Standalone AST utilities.
Byte-indexed string, easy mapping between character and encoded byte index (including 1 past last valid unit). Only positive indices.
Check if s is a valid python identifier. Should be normalized already.
Check if s is a valid python dotted identifier (for modules).
Check if s is a valid python identifier or a star '*'.
Check if s is a valid python dotted identifier or a star '*'.
Check if ast is a valid Constant node for a MatchSingleton.value field.
Check if ast is a valid node for a MatchValue.value field.
Check if ast is a valid node for a MatchMapping.keys field.
Check if asts is a valid target for Assign or For operations. Must be Name, Attribute, Subscript
and / or possibly nested Starred, Tuple and List.
Check if asts is a valid target for Delete operations. Must be Name, Attribute, Subscript and / or
possibly nested Tuple and List. No Starred allowed.
Reduce a mod / Expr wrapped expression or single statement if possible, otherwise return original AST,
None or raise. Also reduces _ExceptHandlers and _match_cases if they are of length 1.
Parameters:
ast:ASTto reduce.multi_mod: Ifastis amodwith not exactly one statements then:True: Return it.False: ReturnNone.type[Exception]: If an exception class is passed then willraise multi_mod(error).
reduce_Expr: Whether to reduce a singleExprnode and return its expression or not.
Get child node at field name in the given parent optionally at the given index idx.
Set child node at field name in the given parent optionally at the given index idx to child.
Does it has type comments?
Really means if the AST is unparse()able and then reparse()able which will get it to this top level AST node
surrounded by the appropriate ast.mod
Return the original mode string that is used to parse to this mod.
Raised in walk2(), compare_asts() and copy_attributes() on compare failure.
Walk two asts simultaneously comparing along the way to ensure they have the same structure.
Parameters:
ast1: FirstASTtree (redundant) to walk.ast2: SecondASTtree to walk.cb_primitive: A function to call to compare primitive nodes which is called with the values of the nodes from tree1 and tree2 and the name and index of the field. It should return whether the values compare equal or not, or justTrueif they are being ignored for example.ctx: Whether to comparectxfields or not.recurse: Whether recurse into children or not. With this asFalseit just becomes a compare of two individualASTnodes.skip1: List of nodes in the first tree to skip, will skip the corresponding node in the second tree.skip2: List of nodes in the second tree to skip, will skip the corresponding node in the first tree.
Returns:
Iterator
Compare two trees including possibly locations and type comments using walk2().
Parameters:
ast1: FirstASTtree (redundant) to compare.ast2: SecondASTtree to compare.locs: Whether to compare location attributes or not (lineno,col_offset, etc...).ctx: Whether to comparectxnodes or not.type_comments: Whether to compare type comments or not. Ignored ifcb_primitiveprovided.skip1: List of nodes in the first tree to skip comparing, will skip the corresponding node in the second tree.skip2: List of nodes in the second tree to skip comparing, will skip the corresponding node in the first tree.cb_primitive: Callback for comparing primitives. Is called withcb_primitive(val1, val2, field, idx)and should returnTrueif the two primitives compare same or not. Used to make certain fields always compare same.raise_: Whether to raiseWalkFailon compare fail or just returnFalse.
Returns:
bool: Indicating if the two trees compare equal under given parameters (if return on error allowed byraise_).
Copy attributes from one tree to another using walk2() to walk them both simultaneously and this checking
structure equality in the process. By "attributes" we mean everything specified in src._attributes.
Parameters:
src: SourceASTtree to copy attributes from.dst: DestinationASTtree to copy attributes to.recurse: Whether recurse into children or not. With this asFalseit just becomes a copy of attributes from oneASTnode to another.skip1: List of nodes in the source tree to skip.skip2: List of nodes in the destination tree to skip.raise_: Whether to raiseWalkFailon compare fail or just returnFalse.
Returns:
bool: Indicating if the two trees compare equal during the walk (if return on error allowed byraise_).
Copy a whole tree.
Set all ctx fields in this node and any children which may participate in an assignment (Tuple, List,
Starred, Subscript, Attribute, Name) to the passed ctx type.
WARNING! This will not recurse into elements which have a ctx of the type being set.
Parameters:
asts: SingleAST(will be recursed) or list ofASTnodes (will be consumed, each one will also be recursed) to process.ctx: Theexprt_contextASTtype to set. Any container encountered which matches thisctxwill not be recursed.doit: Whether to actually carry out the assignments or just analyze and return whethere there are candidate locations for assignment.doit=Falseused to query if any context-modifiablectxpresent.
Returns:
bool: Whether any modifications were made or can be made (ifdoit=False).
Walk through an Iterable of AST nodes looking for the first FunctionDef, AsyncFunctionDef, ClassDef or
optionally Assign or AnnAssign which has a name or target or any targets field matching name.
Parameters:
asts:IterableofASTs to search through, e.g. abodylist.name: Name to look for.ass: A domesticated donkey: a sturdy, short-haired animal used as a beast of burden.
Returns:
ASTnode if found matching, elseNone
Return last AST node in the block header before the ':'. Returns None for non-block nodes and things like
Try and empty ExceptHandler nodes or other block nodes which might have normally present fields missing.
Whether ast is enclosed in some kind of delimiters '()', '[]', '{}' when unparse()d or otherwise atomic
like Name, Constant, etc... Node types where this doesn't normally apply like stmt will return True. Tuple
and MatchSequence which can otherwise be ambiguous will normally return True as they unparse() with
delimiters, but can be overridden.
Parameters:
ast: Self-explanatory.unparse_pars_as_atom: What to return forNamedExpr,YieldandYieldFromnode type as theyunparse()with enclosing parentheses. DefaultNoneas falsey value but also distinguishes fromFalse.tuple_as_atom: What to return forTupleas this alwaysunparse()s with parentheses but these are not strictly required for aTuple.matchseq_as_atom: What to return forMatchSequenceas this alwaysunparse()s with brackets but these are not strictly required for aMatchSequence.
Returns:
Trueif is enclosed and no combination with another node can change its precedence,Falseotherwise. Returnsunparse_pars_as_atomvalue forNamedExpr,YieldandYieldFrom,tuple_as_atomvalue forTupleandmatchseq_as_atomforMatchSequenceas those all are special cases.
Get list of all AST children in syntax order. This will include individual fields and aggregate fields like
body all smushed up together into a single flat list. The list may contain None values for example from a Dict
keys field which has ** elements.
Returns whether parentheses are required for the child for the given parent / child combination or not. Both
parent and child BoolOp, BinOp and UnaryOp types should be passed as the type of the op field.
Parameters:
child_type: Type of the childASTnode or of itsopfield if it is aBoolOp,BinOporUnaryOp.parent_type: Type of the parentASTnode or of itsopfield if it is aBoolOp,BinOporUnaryOp.field: The name of the field in the parent where the child resides.flags: Special case flags, individual flags assumedFalseif not passed asTrue:dict_key_None: Parent isDictand the corresponding key isNone, leading to**value. Only has effect iffieldis'value', otherwise no effect.matchas_pat_None: Child isMatchAsand thepatternisNone(just a name).attr_val_int: Parent isAttributeand childvalueis aConstantinteger.star_arglike: Parent isStarredin a place where arglike expressions are allowed (Call.args,ClassDef.basesor unaprenthesized sliceTuple).
Returns:
bool: Whether parentheses are needed around the child for correct parsing or not.
Returns whether parentheses are required for the given parent / child combination or not. Unlike
precedence_require_parens_by_type(), this takes the actual node instances and figures out the respective types
and flags.
Parameters:
child: ChildASTnode.parent: ParentASTnode.field: The name of the field in the parent where the child resides.idx: The optional index of the child in the parent field, orNoneif does not apply.flags: Used to passed in some flags that cannot be determined here, specificallystar_arglike.
Returns:
bool: Whether parentheses are needed around the child for correct parsing or not.