Nodes
CSTNode and its subclasses cover Python’s full grammar in a whitespace-sensitive fashion, forming LibCST’s concrete syntax tree.
Many of these nodes are designed to behave similarly to Python’s abstract syntax tree.
CSTNode
The base node type which all other nodes derive from.
- class libcst.CSTNode[source]
- validate_types_shallow() None[source]
Compares the type annotations on a node’s fields with those field’s actual values at runtime. Raises a TypeError is a mismatch is found.
Only validates the current node, not any of it’s children. For a recursive version, see
validate_types_deep().If you’re using a static type checker (highly recommended), this is useless. However, if your code doesn’t use a static type checker, or if you’re unable to statically type your code for some reason, you can use this method to help validate your tree.
Some (non-typing) validation is done unconditionally during the construction of a node. That validation does not overlap with the work that
validate_types_deep()does.
- validate_types_deep() None[source]
Like
validate_types_shallow(), but recursively validates the whole tree.
- property children: Sequence[CSTNode]
The immediate (not transitive) child CSTNodes of the current node. Various properties on the nodes, such as string values, will not be visited if they are not a subclass of CSTNode.
Iterable properties of the node (e.g. an IndentedBlock’s body) will be flattened into the children’s sequence.
The children will always be returned in the same order that they appear lexically in the code.
- visit(visitor: CSTTransformer | CSTVisitor) _CSTNodeSelfT | RemovalSentinel | FlattenSentinel[_CSTNodeSelfT][source]
Visits the current node, its children, and all transitive children using the given visitor’s callbacks.
- with_changes(**changes: Any) _CSTNodeSelfT[source]
A convenience method for performing mutation-like operations on immutable nodes. Creates a new object of the same type, replacing fields with values from the supplied keyword arguments.
For example, to update the test of an if conditional, you could do:
def leave_If(self, original_node: cst.If, updated_node: cst.If) -> cst.If: new_node = updated_node.with_changes(test=new_conditional) return new_node
new_nodewill have the samebody,orelse, and whitespace fields asupdated_node, but with the updatedtestfield.The accepted arguments match the arguments given to
__init__, however there are no required or positional arguments.TODO: This API is untyped. There’s probably no sane way to type it using pyre’s current feature-set, but we should still think about ways to type this or a similar API in the future.
- deep_clone() _CSTNodeSelfT[source]
Recursively clone the entire tree. The created tree is a new tree has the same representation but different identity.
>>> tree = cst.parse_expression("1+2")
>>> tree.deep_clone() == tree False
>>> tree == tree True
>>> tree.deep_equals(tree.deep_clone()) True
- deep_equals(other: CSTNode) bool[source]
Recursively inspects the entire tree under
selfandotherto determine if the two trees are equal by representation instead of identity (==).
- deep_replace(old_node: CSTNode, new_node: CSTNodeT) _CSTNodeSelfT | CSTNodeT[source]
Recursively replaces any instance of
old_nodewithnew_nodeby identity. Use this to avoid nestedwith_changesblocks when you are replacing one of a node’s deep children with a new node. Note that if you have previously modified the tree in a way thatold_nodeappears more than once as a deep child, all instances will be replaced.
- deep_remove(old_node: CSTNode) _CSTNodeSelfT | RemovalSentinel[source]
Recursively removes any instance of
old_nodeby identity. Note that if you have previously modified the tree in a way thatold_nodeappears more than once as a deep child, all instances will be removed.
- with_deep_changes(old_node: CSTNode, **changes: Any) _CSTNodeSelfT[source]
A convenience method for applying
with_changesto a child node. Use this to avoid chains ofwith_changesor combinations ofdeep_replaceandwith_changes.The accepted arguments match the arguments given to the child node’s
__init__.TODO: This API is untyped. There’s probably no sane way to type it using pyre’s current feature-set, but we should still think about ways to type this or a similar API in the future.
Module
A node that represents an entire python module.
- class libcst.Module[source]
Contains some top-level information inferred from the file letting us set correct defaults when printing the tree about global formatting rules. All code parsed with
parse_module()will be encapsulated in a module.- body: Sequence[SimpleStatementLine | BaseCompoundStatement]
A list of zero or more statements that make up this module.
- header: Sequence[EmptyLine]
Normally any whitespace/comments are assigned to the next node visited, but
Moduleis a special case, and comments at the top of the file tend to refer to the module itself, so we assign them to theModuleinstead of the first statement in the body.
Any trailing whitespace/comments found after the last statement.
- encoding: str
The file’s encoding format. When parsing a
bytesobject, this value may be inferred from the contents of the parsed source code. When parsing astr, this value defaults to"utf-8".This value affects how
bytesencodes the source code.
- default_indent: str
The indentation of the file, expressed as a series of tabs and/or spaces. This value is inferred from the contents of the parsed source code by default.
- default_newline: str
The newline of the file, expressed as
\n,\r\n, or\r. This value is inferred from the contents of the parsed source code by default.
- visit(visitor: CSTTransformer | CSTVisitor) _ModuleSelfT[source]
Returns the result of running a visitor over this module.
Moduleoverrides the default visitor entry point to resolve metadata dependencies declared by ‘visitor’.
- property code: str
The string representation of this module, respecting the inferred indentation and newline type.
- property bytes: bytes
The bytes representation of this module, respecting the inferred indentation and newline type, using the current encoding.
- code_for_node(node: CSTNode) str[source]
Generates the code for the given node in the context of this module. This is a method of Module, not CSTNode, because we need to know the module’s default indentation and newline formats.
- property config_for_parsing: PartialParserConfig
Generates a parser config appropriate for passing to a
parse_expression()orparse_statement()call. This is useful when using either parser function to generate code from a string template. By using a generated parser config instead of the default, you can guarantee that trees generated from both statement and expression strings have the same inferred defaults for things like newlines, indents and similar:module = cst.parse_module("pass\n") expression = cst.parse_expression("1 + 2", config=module.config_for_parsing)
Expressions
An expression is anything that represents a value (e.g. it could be returned
from a function). All expressions subclass from BaseExpression.
Expression can be parsed with parse_expression() or as part of a
statement or module using parse_statement() or
parse_module().
- class libcst.BaseExpression[source]
An base class for all expressions.
BaseExpressioncontains no fields.
Names and Object Attributes
- class libcst.Name[source]
A simple variable name. Names are typically used in the context of a variable access, an assignment, or a deletion.
Dotted variable names (
a.b.c) are represented withAttributenodes, and subscripted variable names (a[b]) are represented withSubscriptnodes.- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
- class libcst.Attribute[source]
An attribute reference, such as
x.y.Note that in the case of
x.y.z, the outer attribute will have an attr ofzand the value will be anotherAttributereferencing theyattribute onx:Attribute( value=Attribute( value=Name("x") attr=Name("y") ), attr=Name("z"), )
- value: BaseExpression
An expression which, when evaluated, will produce an object with
attras an attribute.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
Operations and Comparisons
Operation and Comparison nodes combine one or more expressions with an operator.
- class libcst.UnaryOperation[source]
Any generic unary expression, such as
not xor-x.UnaryOperationnodes apply aBaseUnaryOpto an expression.- operator: BaseUnaryOp
The unary operator that applies some operation (e.g. negation) to the
expression.
- expression: BaseExpression
The expression that should be transformed (e.g. negated) by the operator to create a new value.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
- class libcst.BinaryOperation[source]
An operation that combines two expression such as
x << yory + z.BinaryOperationnodes apply aBaseBinaryOpto an expression.Binary operations do not include operations performed with
BaseBooleanOpnodes, such asandoror. Instead, those operations are provided byBooleanOperation.It also does not include support for comparision operators performed with
BaseCompOp, such as<,>=,==,is, orin. Instead, those operations are provided byComparison.- left: BaseExpression
The left hand side of the operation.
- operator: BaseBinaryOp
The actual operator such as
<<or+that combines theleftandrightexpressions.
- right: BaseExpression
The right hand side of the operation.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
- class libcst.BooleanOperation[source]
An operation that combines two booleans such as
x or yorz and wBooleanOperationnodes apply aBaseBooleanOpto an expression.Boolean operations do not include operations performed with
BaseBinaryOpnodes, such as+or<<. Instead, those operations are provided byBinaryOperation.It also does not include support for comparision operators performed with
BaseCompOp, such as<,>=,==,is, orin. Instead, those operations are provided byComparison.- left: BaseExpression
The left hand side of the operation.
- operator: BaseBooleanOp
The actual operator such as
andororthat combines theleftandrightexpressions.
- right: BaseExpression
The right hand side of the operation.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
- class libcst.Comparison[source]
A comparison between multiple values such as
x < y,x < y < z, orx in [y, z]. These comparisions typically result in boolean values.Unlike
BinaryOperationandBooleanOperation, comparisons are not restricted to a left and right child. Instead they can contain an arbitrary number ofComparisonTargetchildren.x < y < zis not equivalent to(x < y) < zorx < (y < z). Instead, it’s roughly equivalent tox < y and y < z.For more details, see Python’s documentation on comparisons.
# x < y < z Comparison( Name("x"), [ ComparisonTarget(LessThan(), Name("y")), ComparisonTarget(LessThan(), Name("z")), ], )
- left: BaseExpression
The first value in the full sequence of values to compare. This value will be compared against the first value in
comparisions.
- comparisons: Sequence[ComparisonTarget]
Pairs of
BaseCompOpoperators and expression values to compare. These come afterleft. Each value is compared against the value before and after itself in the sequence.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
- class libcst.ComparisonTarget[source]
A target for a
Comparison. Owns the comparison operator and the value to the right of the operator.- operator: BaseCompOp
A comparison operator such as
<,>=,==,is, orin.
- comparator: BaseExpression
The right hand side of the comparison operation.
Control Flow
- class libcst.Asynchronous[source]
Used by asynchronous function definitions, as well as
async forandasync with.- whitespace_after: SimpleWhitespace
Any space that appears directly after this async keyword.
- class libcst.Await[source]
An await expression. Await expressions are only valid inside the body of an asynchronous
FunctionDefor (as of Python 3.7) inside of an asynchronousGeneratorExpnodes.- expression: BaseExpression
The actual expression we need to wait for.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
- whitespace_after_await: BaseParenthesizableWhitespace
Whitespace that appears after the
asynckeyword, but before the innerexpression.
- class libcst.Yield[source]
A yield expression similar to
yield xoryield from fun().To learn more about the ways that yield can be used in generators, refer to Python’s language reference.
- value: BaseExpression | From | None
The value yielded from the generator, in the case of a
Fromclause, a sub-generator to iterate over.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
- whitespace_after_yield: BaseParenthesizableWhitespace | MaybeSentinel
Whitespace after the
yieldkeyword, but before thevalue.
- class libcst.From[source]
A
from xstanza in aYieldorRaise.- item: BaseExpression
The expression that we are yielding/raising from.
- whitespace_before_from: BaseParenthesizableWhitespace | MaybeSentinel
The whitespace at the very start of this node.
- whitespace_after_from: BaseParenthesizableWhitespace
The whitespace after the
fromkeyword, but before theitem.
- class libcst.IfExp[source]
An if expression of the form
body if test else orelse.If statements are provided by
IfandElsenodes.- test: BaseExpression
The test to perform.
- body: BaseExpression
The expression to evaluate when the test is true.
- orelse: BaseExpression
The expression to evaluate when the test is false.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
- whitespace_before_if: BaseParenthesizableWhitespace
Whitespace after the
bodyexpression, but before theifkeyword.
- whitespace_after_if: BaseParenthesizableWhitespace
Whitespace after the
ifkeyword, but before thetestclause.
- whitespace_before_else: BaseParenthesizableWhitespace
Whitespace after the
testexpression, but before theelsekeyword.
- whitespace_after_else: BaseParenthesizableWhitespace
Whitespace after the
elsekeyword, but before theorelseexpression.
Lambdas and Function Calls
- class libcst.Lambda[source]
A lambda expression that creates an anonymous function.
Lambda( params=Parameters([Param(Name("arg"))]), body=Ellipsis(), )
Represents the following code:
lambda arg: ...
Named functions statements are provided by
FunctionDef.- params: Parameters
The arguments to the lambda. This is similar to the arguments on a
FunctionDef, however lambda arguments are not allowed to have anAnnotation.
- body: BaseExpression
The value that the lambda computes and returns when called.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
- whitespace_after_lambda: BaseParenthesizableWhitespace | MaybeSentinel
Whitespace after the lambda keyword, but before any argument or the colon.
- class libcst.Call[source]
An expression representing a function call, such as
do_math(1, 2)orpicture.post_on_instagram().Function calls consist of a function name and a sequence of arguments wrapped in
Argnodes.- func: BaseExpression
The expression resulting in a callable that we are to call. Often a
NameorAttribute.
- args: Sequence[Arg]
The arguments to pass to the resulting callable. These may be a mix of positional arguments, keyword arguments, or “starred” arguments.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation. These are not the parenthesis before and after the list of
args, but rather arguments around the entire call expression, such as(( do_math(1, 2) )).
- whitespace_after_func: BaseParenthesizableWhitespace
Whitespace after the
funcname, but before the opening parenthesis.
- whitespace_before_args: BaseParenthesizableWhitespace
Whitespace after the opening parenthesis but before the first argument (if there are any). Whitespace after the last argument but before the closing parenthesis is owned by the last
Argif it exists.
- class libcst.Arg[source]
A single argument to a
Call.This supports named keyword arguments in the form of
keyword=valueand variable argument expansion using*argsor**kwargssyntax.- value: BaseExpression
The argument expression itself, not including a preceding keyword, or any of the surrounding the value, like a comma or asterisks.
- equal: AssignEqual | MaybeSentinel
The equal sign used to denote assignment if there is a keyword.
- comma: Comma | MaybeSentinel
Any trailing comma.
- star: Literal['', '*', '**']
A string with zero, one, or two asterisks appearing before the name. These are expanded into variable number of positional or keyword arguments.
- whitespace_after_star: BaseParenthesizableWhitespace
Whitespace after the
star(if it exists), but before thekeywordorvalue(if no keyword is provided).
- whitespace_after_arg: BaseParenthesizableWhitespace
Whitespace after this entire node. The
Commanode (if it exists) may also store some trailing whitespace.
Literal Values
- class libcst.Ellipsis[source]
An ellipsis
.... When used as an expression, it evaluates to the Ellipsis constant. Ellipsis are often used as placeholders in code or in conjunction withSubscriptElement.- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
Numbers
- class libcst.BaseNumber[source]
A type such as
Integer,Float, orImaginarythat can be used anywhere that you need to explicitly take any number type.
- class libcst.Integer[source]
- value: str
A string representation of the integer, such as
"100000"or100_000.To convert this string representation to an
int, use the calculated propertyevaluated_value.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
- property evaluated_value: int
Return an
ast.literal_eval()evaluated int ofvalue.
- class libcst.Float[source]
- value: str
A string representation of the floating point number, such as
"0.05",".050", or"5e-2".To convert this string representation to an
float, use the calculated propertyevaluated_value.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
- property evaluated_value: float
Return an
ast.literal_eval()evaluated float ofvalue.
- class libcst.Imaginary[source]
- value: str
A string representation of the imaginary (complex) number, such as
"2j".To convert this string representation to an
complex, use the calculated propertyevaluated_value.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
- property evaluated_value: complex
Return an
ast.literal_eval()evaluated complex ofvalue.
Strings
- class libcst.BaseString[source]
A type that can be used anywhere that you need to take any string. This includes
SimpleString,ConcatenatedString, andFormattedString.
- class libcst.SimpleString[source]
Any sort of literal string expression that is not a
FormattedString(f-string), including triple-quoted multi-line strings.- value: str
The texual representation of the string, including quotes, prefix characters, and any escape characters present in the original source code , such as
r"my string\n". To remove the quotes and interpret any escape characters, use the calculated propertyevaluated_value.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precidence dictation.
- property prefix: str
Returns the string’s prefix, if any exists. The prefix can be
r,u,b,brorrb.
- property quote: Literal['"', "'", '"""', "'''"]
Returns the quotation used to denote the string. Can be either
',",'''or""".
- property raw_value: str
Returns the raw value of the string as it appears in source, without the beginning or end quotes and without the prefix. This is often useful when constructing transforms which need to manipulate strings in source code.
- property evaluated_value: str
Return an
ast.literal_eval()evaluated str ofvalue.
- class libcst.ConcatenatedString[source]
Represents an implicitly concatenated string, such as:
"abc" "def" == "abcdef"
Warning
This is different from two strings joined in a
BinaryOperationwith anAddoperator, and is sometimes viewed as an antifeature of Python.- left: SimpleString | FormattedString
String on the left of the concatenation.
- right: SimpleString | FormattedString | ConcatenatedString
String on the right of the concatenation.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precidence dictation.
- whitespace_between: BaseParenthesizableWhitespace
Whitespace between the
leftandrightsubstrings.
- property evaluated_value: str | None
Return an
ast.literal_eval()evaluated str of recursively concatenatedleftandrightif and only if bothleftandrightare composed bySimpleStringorConcatenatedString(FormattedStringcannot be evaluated).
Formatted Strings (f-strings)
- class libcst.FormattedString[source]
An “f-string”. These formatted strings are string literals prefixed by the letter “f”. An f-string may contain interpolated expressions inside curly braces (
{and}).F-strings are defined in PEP 498 and documented in Python’s language reference.
>>> import libcst as cst >>> cst.parse_expression('f"ab{cd}ef"') FormattedString( parts=[ FormattedStringText( value='ab', ), FormattedStringExpression( expression=Name( value='cd', lpar=[], rpar=[], ), conversion=None, format_spec=None, whitespace_before_expression=SimpleWhitespace( value='', ), whitespace_after_expression=SimpleWhitespace( value='', ), ), FormattedStringText( value='ef', ), ], start='f"', end='"', lpar=[], rpar=[], )
- parts: Sequence[BaseFormattedStringContent]
A formatted string is composed as a series of
FormattedStringTextandFormattedStringExpressionparts.
- end: Literal['"', "'", '"""', "'''"]
The trailing quote. This must match the type of quote used in
start.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precidence dictation.
- class libcst.BaseFormattedStringContent[source]
The base type for
FormattedStringTextandFormattedStringExpression. AFormattedStringis composed of a sequence ofBaseFormattedStringContentparts.
- class libcst.FormattedStringText[source]
Part of a
FormattedStringthat is not inside curly braces ({or}). For example, in:f"ab{cd}ef"
abandefareFormattedStringTextnodes, but{cd}is aFormattedStringExpression.
- class libcst.FormattedStringExpression[source]
Part of a
FormattedStringthat is inside curly braces ({or}), including the surrounding curly braces. For example, in:f"ab{cd}ef"
{cd}is aFormattedStringExpression, butabandefareFormattedStringTextnodes.An f-string expression may contain
conversionandformat_specsuffixes that control how the expression is converted to a string. See Python’s language reference for details.- expression: BaseExpression
The expression we will evaluate and render when generating the string.
- format_spec: Sequence[BaseFormattedStringContent] | None
An optional format specifier following the format specification mini-language.
- whitespace_before_expression: BaseParenthesizableWhitespace
Whitespace after the opening curly brace (
{), but before theexpression.
- whitespace_after_expression: BaseParenthesizableWhitespace
Whitespace after the
expression, but before theconversion,format_specand the closing curly brace (}). Python does not allow whitespace inside or after aconversionorformat_spec.
- equal: AssignEqual | None
Equal sign for formatted string expression uses self-documenting expressions, such as
f"{x=}". See the Python 3.8 release notes.
Collections
Simple Collections
- class libcst.Tuple[source]
An immutable literal tuple. Tuples are often (but not always) parenthesized.
Tuple([ Element(Integer("1")), Element(Integer("2")), StarredElement(Name("others")), ])
generates the following code:
(1, 2, *others)
- elements: Sequence[BaseElement]
A sequence containing all the
ElementandStarredElementnodes in the tuple.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
- class libcst.BaseList[source]
A base class for
ListandListComp, which both result in a list object when evaluated.- lbracket: LeftSquareBracket = Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object>,default_factory=<function CSTNode.field.<locals>.<lambda>>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE object>,_field_type=None)
- rbracket: RightSquareBracket = Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object>,default_factory=<function CSTNode.field.<locals>.<lambda>>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE object>,_field_type=None)
Brackets surrounding the list.
- rpar: Sequence[RightParen] = ()
Sequence of parenthesis for precedence dictation.
- class libcst.List[source]
A mutable literal list.
List([ Element(Integer("1")), Element(Integer("2")), StarredElement(Name("others")), ])
generates the following code:
[1, 2, *others]
List comprehensions are represented with a
ListCompnode.- elements: Sequence[BaseElement]
A sequence containing all the
ElementandStarredElementnodes in the list.
- lbracket: LeftSquareBracket
- rbracket: RightSquareBracket
Brackets surrounding the list.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
- class libcst.BaseSet[source]
An abstract base class for
SetandSetComp, which both result in a set object when evaluated.
- class libcst.Set[source]
A mutable literal set.
Set([ Element(Integer("1")), Element(Integer("2")), StarredElement(Name("others")), ])
generates the following code:
{1, 2, *others}
Set comprehensions are represented with a
SetCompnode.- elements: Sequence[BaseElement]
A sequence containing all the
ElementandStarredElementnodes in the set.
- lbrace: LeftCurlyBrace
- rbrace: RightCurlyBrace
Braces surrounding the set.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
Simple Collection Elements
- class libcst.BaseElement[source]
An element of a literal list, tuple, or set. For elements of a literal dict, see BaseDictElement.
- class libcst.Element[source]
A simple value in a literal
List,Tuple, orSet. These a literal collection may also contain aStarredElement.If you’re using a literal
Dict, seeDictElementinstead.- value: BaseExpression
- comma: Comma | MaybeSentinel
A trailing comma. By default, we’ll only insert a comma if one is required.
- class libcst.StarredElement[source]
A starred
*valueelement that expands to represent multiple values in a literalList,Tuple, orSet.If you’re using a literal
Dict, seeStarredDictElementinstead.If this node owns parenthesis, those parenthesis wrap the leading asterisk, but not the trailing comma. For example:
StarredElement( cst.Name("el"), comma=cst.Comma(), lpar=[cst.LeftParen()], rpar=[cst.RightParen()], )
will generate:
(*el),
- value: BaseExpression
- comma: Comma | MaybeSentinel
A trailing comma. By default, we’ll only insert a comma if one is required.
- rpar: Sequence[RightParen]
Parentheses after the value, but before a comma (if there is one).
- whitespace_before_value: BaseParenthesizableWhitespace
Whitespace between the leading asterisk and the value expression.
Dictionaries
- class libcst.BaseDict[source]
An abstract base class for
DictandDictComp, which both result in a dict object when evaluated.
- class libcst.Dict[source]
A literal dictionary. Key-value pairs are stored in
elementsusingDictElementnodes.It’s possible to expand one dictionary into another, as in
{k: v, **expanded}. Expanded elements are stored asStarredDictElementnodes.Dict([ DictElement(Name("k1"), Name("v1")), DictElement(Name("k2"), Name("v2")), StarredDictElement(Name("expanded")), ])
generates the following code:
{k1: v1, k2: v2, **expanded}
- elements: Sequence[BaseDictElement]
- lbrace: LeftCurlyBrace
- rbrace: RightCurlyBrace
Braces surrounding the set or dict.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
Dictionary Elements
- class libcst.BaseDictElement[source]
An element of a literal dict. For elements of a list, tuple, or set, see BaseElement.
- class libcst.DictElement[source]
A simple
key: valuepair that represents a single entry in a literalDict.Dictnodes may also contain aStarredDictElement.If you’re using a literal
List,Tuple, orSet, seeElementinstead.- key: BaseExpression
- value: BaseExpression
- comma: Comma | MaybeSentinel
A trailing comma. By default, we’ll only insert a comma if one is required.
- whitespace_before_colon: BaseParenthesizableWhitespace
Whitespace after the key, but before the colon in
key : value.
- whitespace_after_colon: BaseParenthesizableWhitespace
Whitespace after the colon, but before the value in
key : value.
- class libcst.StarredDictElement[source]
A starred
**valueelement that expands to represent multiple values in a literalDict.If you’re using a literal
List,Tuple, orSet, seeStarredElementinstead.Unlike
StarredElement, this node does not own left or right parenthesis, but thevaluefield may still contain parenthesis. This is due to some asymmetry in Python’s grammar.- value: BaseExpression
- comma: Comma | MaybeSentinel
A trailing comma. By default, we’ll only insert a comma if one is required.
- whitespace_before_value: BaseParenthesizableWhitespace
Whitespace between the leading asterisks and the value expression.
Comprehensions
- class libcst.BaseComp[source]
A base class for all comprehension and generator expressions, including
GeneratorExp,ListComp,SetComp, andDictComp.
- class libcst.BaseSimpleComp[source]
The base class for
ListComp,SetComp, andGeneratorExp.DictCompis not aBaseSimpleComp, because it useskeyandvalue.- elt: BaseAssignTargetExpression
The expression evaluated during each iteration of the comprehension. This lexically comes before the
for_inclause, but it is semantically the inner-most element, evaluated inside thefor_inclause.
- class libcst.GeneratorExp[source]
A generator expression.
eltrepresents the value yielded for each item inCompFor.iter.All
for ... in ...andif ...clauses are stored as a recursiveCompFordata structure insidefor_in.- elt: BaseAssignTargetExpression
The expression evaluated and yielded during each iteration of the generator.
- for_in: CompFor
The
for ... in ... if ...clause that comes afterelt. This may be a nested structure for nested comprehensions. SeeCompForfor details.
- rpar: Sequence[RightParen]
Sequence of parentheses for precedence dictation. Generator expressions must always be parenthesized. However, if a generator expression is the only argument inside a function call, the enclosing
Callnode may own the parentheses instead.
- class libcst.ListComp[source]
A list comprehension.
eltrepresents the value stored for each item inCompFor.iter.All
for ... in ...andif ...clauses are stored as a recursiveCompFordata structure insidefor_in.- elt: BaseAssignTargetExpression
The expression evaluated and stored during each iteration of the comprehension.
- for_in: CompFor
The
for ... in ... if ...clause that comes afterelt. This may be a nested structure for nested comprehensions. SeeCompForfor details.
- lbracket: LeftSquareBracket
- rbracket: RightSquareBracket
Brackets surrounding the list comprehension.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
- class libcst.SetComp[source]
A set comprehension.
eltrepresents the value stored for each item inCompFor.iter.All
for ... in ...andif ...clauses are stored as a recursiveCompFordata structure insidefor_in.- elt: BaseAssignTargetExpression
The expression evaluated and stored during each iteration of the comprehension.
- for_in: CompFor
The
for ... in ... if ...clause that comes afterelt. This may be a nested structure for nested comprehensions. SeeCompForfor details.
- lbrace: LeftCurlyBrace
- rbrace: RightCurlyBrace
Braces surrounding the set comprehension.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
- class libcst.DictComp[source]
A dictionary comprehension.
keyandvaluerepresent the dictionary entry evaluated for each item.All
for ... in ...andif ...clauses are stored as a recursiveCompFordata structure insidefor_in.- key: BaseAssignTargetExpression
The key inserted into the dictionary during each iteration of the comprehension.
- value: BaseAssignTargetExpression
The value associated with the
keyinserted into the dictionary during each iteration of the comprehension.
- for_in: CompFor
The
for ... in ... if ...clause that lexically comes afterkeyandvalue. This may be a nested structure for nested comprehensions. SeeCompForfor details.
- lbrace: LeftCurlyBrace
- rbrace: RightCurlyBrace
Braces surrounding the dict comprehension.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
- whitespace_before_colon: BaseParenthesizableWhitespace
Whitespace after the key, but before the colon in
key : value.
- whitespace_after_colon: BaseParenthesizableWhitespace
Whitespace after the colon, but before the value in
key : value.
- class libcst.CompFor[source]
One
forclause in aBaseComp, or a nested hierarchy offorclauses.Nested loops in comprehensions are difficult to get right, but they can be thought of as a flat representation of nested clauses.
elt for a in b for c in d if ecan be thought of as:for a in b: for c in d: if e: yield elt
And that would form the following CST:
ListComp( elt=Name("elt"), for_in=CompFor( target=Name("a"), iter=Name("b"), ifs=[], inner_comp_for=CompFor( target=Name("c"), iter=Name("d"), ifs=[ CompIf( test=Name("e"), ), ], ), ), )
Normal
forstatements are provided byFor.- target: BaseAssignTargetExpression
The target to assign a value to in each iteration of the loop. This is different from
GeneratorExp.elt,ListComp.elt,SetComp.elt, andkeyandvalueinDictComp, because it doesn’t directly effect the value of resulting generator, list, set, or dict.
- iter: BaseExpression
The value to iterate over. Every value in
iteris stored intarget.
- ifs: Sequence[CompIf]
Zero or more conditional clauses that control this loop. If any of these tests fail, the
targetitem is skipped.if a if b if c
has similar semantics to:
if a and b and c
- inner_for_in: CompFor | None
Another
CompFornode used to form nested loops. Nested comprehensions can be useful, but they tend to be difficult to read and write. As a result they are uncommon.
- asynchronous: Asynchronous | None
An optional async modifier that appears before the
forkeyword.
- whitespace_before: BaseParenthesizableWhitespace
Whitespace that appears at the beginning of this node, before the
forandasynckeywords.
- whitespace_after_for: BaseParenthesizableWhitespace
Whitespace appearing after the
forkeyword, but before thetarget.
- whitespace_before_in: BaseParenthesizableWhitespace
Whitespace appearing after the
target, but before theinkeyword.
- whitespace_after_in: BaseParenthesizableWhitespace
Whitespace appearing after the
inkeyword, but before theiter.
- class libcst.CompIf[source]
A conditional clause in a
CompFor, used as part of a generator or comprehension expression.If the
testfails, the current element in theCompForwill be skipped.- test: BaseExpression
An expression to evaluate. When interpreted, Python will coerce it to a boolean.
- whitespace_before: BaseParenthesizableWhitespace
Whitespace before the
ifkeyword.
- whitespace_before_test: BaseParenthesizableWhitespace
Whitespace after the
ifkeyword, but before thetestexpression.
Subscripts and Slices
- class libcst.Subscript[source]
A indexed subscript reference (
Index) such asx[2], aSlicesuch asx[1:-1], or an extended slice (SubscriptElement) such asx[1:2, 3].- value: BaseExpression
The left-hand expression which, when evaluated, will be subscripted, such as
xinx[2].
- slice: Sequence[SubscriptElement]
The
SubscriptElementto extract from thevalue.
- lbracket: LeftSquareBracket
- rbracket: RightSquareBracket
Brackets after the
valuesurrounding theslice.
- rpar: Sequence[RightParen]
Sequence of parenthesis for precedence dictation.
- whitespace_after_value: BaseParenthesizableWhitespace
Whitespace after the
value, but before thelbracket.
- class libcst.BaseSlice[source]
Any slice type that can slot into a
SubscriptElement. This node is purely for typing.
- class libcst.Index[source]
Any index as passed to a
Subscript. Inx[2], this would be the2value.- value: BaseExpression
The index value itself.
- star: Literal['*'] | None
An optional string with an asterisk appearing before the name. This is expanded into variable number of positional arguments. See PEP-646
- whitespace_after_star: BaseParenthesizableWhitespace | None
Whitespace after the
star(if it exists), but before thevalue.
- class libcst.Slice[source]
Any slice operation in a
Subscript, such as1:,2:3:4, etc.Note that the grammar does NOT allow parenthesis around a slice so they are not supported here.
- lower: BaseExpression | None
The lower bound in the slice, if present
- upper: BaseExpression | None
The upper bound in the slice, if present
- step: BaseExpression | None
The step in the slice, if present
- second_colon: Colon | MaybeSentinel
The second slice operator, usually omitted
- class libcst.SubscriptElement[source]
Part of a sequence of slices in a
Subscript, such as1:2, 3. This is not used in Python’s standard library, but it is used in some third-party libraries. For example, NumPy uses it to select values and ranges from multi-dimensional arrays.- comma: Comma | MaybeSentinel
A separating comma, with any whitespace it owns.
Parenthesis, Brackets, and Braces
- class libcst.LeftParen[source]
Used by various nodes to denote a parenthesized section. This doesn’t own the whitespace to the left of it since this is owned by the parent node.
- whitespace_after: BaseParenthesizableWhitespace
Any space that appears directly after this left parenthesis.
- class libcst.RightParen[source]
Used by various nodes to denote a parenthesized section. This doesn’t own the whitespace to the right of it since this is owned by the parent node.
- whitespace_before: BaseParenthesizableWhitespace
Any space that appears directly after this left parenthesis.
- class libcst.LeftSquareBracket[source]
Used by various nodes to denote a subscript or list section. This doesn’t own the whitespace to the left of it since this is owned by the parent node.
- whitespace_after: BaseParenthesizableWhitespace
Any space that appears directly after this left square bracket.
- class libcst.RightSquareBracket[source]
Used by various nodes to denote a subscript or list section. This doesn’t own the whitespace to the right of it since this is owned by the parent node.
- whitespace_before: BaseParenthesizableWhitespace
Any space that appears directly before this right square bracket.
- class libcst.LeftCurlyBrace[source]
Used by various nodes to denote a dict or set. This doesn’t own the whitespace to the left of it since this is owned by the parent node.
- whitespace_after: BaseParenthesizableWhitespace
Any space that appears directly after this left curly brace.
- class libcst.RightCurlyBrace[source]
Used by various nodes to denote a dict or set. This doesn’t own the whitespace to the right of it since this is owned by the parent node.
- whitespace_before: BaseParenthesizableWhitespace
Any space that appears directly before this right curly brace.
Statements
Statements represent a “line of code” or a control structure with other lines of
code, such as an If block.
All statements subclass from BaseSmallStatement or
BaseCompoundStatement.
Statements can be parsed with parse_statement() or as part of a
module using parse_module().
Simple Statements
Statements which at most have expressions as child attributes.
- class libcst.BaseSmallStatement[source]
Encapsulates a small statement, like
delorpass, and optionally adds a trailing semicolon. A small statement is always contained inside aSimpleStatementLineorSimpleStatementSuite. This exists to simplify type definitions and isinstance checks.- semicolon: Semicolon | MaybeSentinel = 1
An optional semicolon that appears after a small statement. This is optional for the last small statement in a
SimpleStatementLineorSimpleStatementSuite, but all other small statements inside a simple statement must contain a semicolon to disambiguate multiple small statements on the same line.
- class libcst.AnnAssign[source]
An assignment statement such as
x: int = 5orx: int. This only allows for one assignment target unlikeAssignbut it includes a variable annotation. Also unlikeAssign, the assignment target is optional, as it is possible to annotate an expression without assigning to it.- target: BaseAssignTargetExpression
The target that is being annotated and possibly assigned to.
- annotation: Annotation
The annotation for the target.
- value: BaseExpression | None
The optional expression being assigned to the target.
- equal: AssignEqual | MaybeSentinel
The equals sign used to denote assignment if there is a value.
- semicolon: Semicolon | MaybeSentinel
Optional semicolon when this is used in a statement line. This semicolon owns the whitespace on both sides of it when it is used.
- class libcst.Assert[source]
An assert statement such as
assert x > 5orassert x > 5, 'Uh oh!'- test: BaseExpression
The test we are going to assert on.
- msg: BaseExpression | None
The optional message to display if the test evaluates to a falsey value.
- comma: Comma | MaybeSentinel
A comma separating test and message, if there is a message.
- whitespace_after_assert: SimpleWhitespace
Whitespace appearing after the
assertkeyword and before the test.
- semicolon: Semicolon | MaybeSentinel
Optional semicolon when this is used in a statement line. This semicolon owns the whitespace on both sides of it when it is used.
- class libcst.Assign[source]
An assignment statement such as
x = yorx = y = z. UnlikeAnnAssign, this does not allow type annotations but does allow for multiple targets.- targets: Sequence[AssignTarget]
One or more targets that are being assigned to.
- value: BaseExpression
The expression being assigned to the targets.
- semicolon: Semicolon | MaybeSentinel
Optional semicolon when this is used in a statement line. This semicolon owns the whitespace on both sides of it when it is used.
- class libcst.AugAssign[source]
An augmented assignment statement, such as
x += 5.- target: BaseAssignTargetExpression
Target that is being operated on and assigned to.
- operator: BaseAugOp
The augmented assignment operation being performed.
- value: BaseExpression
The value used with the above operator to calculate the new assignment.
- semicolon: Semicolon | MaybeSentinel
Optional semicolon when this is used in a statement line. This semicolon owns the whitespace on both sides of it when it is used.
- class libcst.Break[source]
Represents a
breakstatement, which is used to break out of aFororWhileloop early.- semicolon: Semicolon | MaybeSentinel
Optional semicolon when this is used in a statement line. This semicolon owns the whitespace on both sides of it when it is used.
- class libcst.Continue[source]
Represents a
continuestatement, which is used to skip to the next iteration in aFororWhileloop.- semicolon: Semicolon | MaybeSentinel
Optional semicolon when this is used in a statement line. This semicolon owns the whitespace on both sides of it when it is used.
- class libcst.Del[source]
Represents a
delstatement.delis always followed by a target.- target: BaseDelTargetExpression
The target expression will be deleted. This can be a name, a tuple, an item of a list, an item of a dictionary, or an attribute.
- whitespace_after_del: SimpleWhitespace
The whitespace after the
delkeyword.
- semicolon: Semicolon | MaybeSentinel
Optional semicolon when this is used in a statement line. This semicolon owns the whitespace on both sides of it when it is used.
- class libcst.Expr[source]
An expression used as a statement, where the result is unused and unassigned. The most common place you will find this is in function calls where the return value is unneeded.
- value: BaseExpression
The expression itself. Python will evaluate the expression but not assign the result anywhere.
- semicolon: Semicolon | MaybeSentinel
Optional semicolon when this is used in a statement line. This semicolon owns the whitespace on both sides of it when it is used.
- class libcst.Global[source]
A
globalstatement.- whitespace_after_global: SimpleWhitespace
Whitespace appearing after the
globalkeyword and before the first name.
- semicolon: Semicolon | MaybeSentinel
Optional semicolon when this is used in a statement line. This semicolon owns the whitespace on both sides of it when it is used.
- class libcst.Import[source]
An
importstatement.- names: Sequence[ImportAlias]
One or more names that are being imported, with optional local aliases.
- semicolon: Semicolon | MaybeSentinel
Optional semicolon when this is used in a statement line. This semicolon owns the whitespace on both sides of it when it is used.
- whitespace_after_import: SimpleWhitespace
The whitespace that appears after the
importkeyword but before the first import alias.
- class libcst.ImportFrom[source]
A
from x import ystatement.- module: Attribute | Name | None
Name or Attribute node representing the module we’re importing from. This is optional as
ImportFromallows purely relative imports.
- names: Sequence[ImportAlias] | ImportStar
One or more names that are being imported from the specified module, with optional local aliases.
- rpar: RightParen | None
Optional close parenthesis for multi-line import continuation.
- semicolon: Semicolon | MaybeSentinel
Optional semicolon when this is used in a statement line. This semicolon owns the whitespace on both sides of it when it is used.
- whitespace_after_from: SimpleWhitespace
The whitespace that appears after the
fromkeyword but before the module and any relative import dots.
- whitespace_before_import: SimpleWhitespace
The whitespace that appears after the module but before the
importkeyword.
- whitespace_after_import: SimpleWhitespace
The whitespace that appears after the
importkeyword but before the first import name or optional left paren.
- class libcst.Nonlocal[source]
A
nonlocalstatement.- whitespace_after_nonlocal: SimpleWhitespace
Whitespace appearing after the
globalkeyword and before the first name.
- semicolon: Semicolon | MaybeSentinel
Optional semicolon when this is used in a statement line. This semicolon owns the whitespace on both sides of it when it is used.
- class libcst.Pass[source]
Represents a
passstatement.- semicolon: Semicolon | MaybeSentinel
Optional semicolon when this is used in a statement line. This semicolon owns the whitespace on both sides of it when it is used.
- class libcst.Raise[source]
A
raise excorraise exc from causestatement.- exc: BaseExpression | None
The exception that we should raise.
- cause: From | None
Optionally, a
from causeclause to allow us to raise an exception out of another exception’s context.
- whitespace_after_raise: SimpleWhitespace | MaybeSentinel
Any whitespace appearing between the
raisekeyword and the exception.
- semicolon: Semicolon | MaybeSentinel
Optional semicolon when this is used in a statement line. This semicolon owns the whitespace on both sides of it when it is used.
- class libcst.Return[source]
Represents a
returnor areturn xstatement.- value: BaseExpression | None
The optional expression that will be evaluated and returned.
- whitespace_after_return: SimpleWhitespace | MaybeSentinel
Optional whitespace after the
returnkeyword before the optional value expression.
- semicolon: Semicolon | MaybeSentinel
Optional semicolon when this is used in a statement line. This semicolon owns the whitespace on both sides of it when it is used.
Compound Statements
Statements that have one or more statement blocks as a child attribute.
- class libcst.BaseCompoundStatement[source]
Encapsulates a compound statement, like
if True: passorwhile True: pass. This exists to simplify type definitions and isinstance checks.Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way. In general, compound statements span multiple lines, although in simple incarnations a whole compound statement may be contained in one line.
- class libcst.ClassDef[source]
A class definition.
- lpar: LeftParen | MaybeSentinel
Optional open parenthesis used when there are bases or keywords.
- rpar: RightParen | MaybeSentinel
Optional close parenthesis used when there are bases or keywords.
- leading_lines: Sequence[EmptyLine]
Leading empty lines and comments before the first decorator. We assume any comments before the first decorator are owned by the class definition itself. If there are no decorators, this will still contain all of the empty lines and comments before the class definition.
- lines_after_decorators: Sequence[EmptyLine]
Empty lines and comments between the final decorator and the
ClassDefnode. In the case of no decorators, this will be empty.
- whitespace_after_class: SimpleWhitespace
Whitespace after the
classkeyword and before the class name.
- whitespace_after_name: SimpleWhitespace
Whitespace after the class name and before the opening parenthesis for the bases and keywords.
- whitespace_before_colon: SimpleWhitespace
Whitespace after the closing parenthesis or class name and before the colon.
- class libcst.For[source]
A
for target in iterstatement.- target: BaseAssignTargetExpression
The target of the iterator in the for statement.
- iter: BaseExpression
The iterable expression we will loop over.
- orelse: Else | None
An optional else case which will be executed if there is no
Breakstatement encountered while looping.
- asynchronous: Asynchronous | None
Optional async modifier, if this is an async for statement.
- whitespace_after_for: SimpleWhitespace
Whitespace after the
forkeyword and before the target.
- whitespace_before_in: SimpleWhitespace
Whitespace after the target and before the
inkeyword.
- whitespace_after_in: SimpleWhitespace
Whitespace after the
inkeyword and before the iter.
- whitespace_before_colon: SimpleWhitespace
Whitespace after the iter and before the colon.
- class libcst.FunctionDef[source]
A function definition.
- params: Parameters
The function parameters. Present even if there are no params.
- decorators: Sequence[Decorator]
Sequence of decorators applied to this function. Decorators are listed in order that they appear in source (top to bottom) as apposed to the order that they are applied to the function at runtime.
- returns: Annotation | None
An optional return annotation, if the function is annotated.
- asynchronous: Asynchronous | None
Optional async modifier, if this is an async function.
- leading_lines: Sequence[EmptyLine]
Leading empty lines and comments before the first decorator. We assume any comments before the first decorator are owned by the function definition itself. If there are no decorators, this will still contain all of the empty lines and comments before the function definition.
- lines_after_decorators: Sequence[EmptyLine]
Empty lines and comments between the final decorator and the
FunctionDefnode. In the case of no decorators, this will be empty.
- whitespace_after_def: SimpleWhitespace
Whitespace after the
defkeyword and before the function name.
- whitespace_after_name: SimpleWhitespace
Whitespace after the function name and before the opening parenthesis for the parameters.
- whitespace_before_params: BaseParenthesizableWhitespace
Whitespace after the opening parenthesis for the parameters but before the first param itself.
- whitespace_before_colon: SimpleWhitespace
Whitespace after the closing parenthesis or return annotation and before the colon.
- class libcst.If[source]
An
ifstatement.testholds a single test expression.elifclauses don’t have a special representation in the AST, but rather appear as extraIfnodes within theorelsesection of the previous one.- test: BaseExpression
The expression that, when evaluated, should give us a truthy/falsey value.
- orelse: If | Else | None
An optional
eliforelseclause.Ifsignifies anelifblock.Elsesignifies anelseblock.Nonesignifies noelseorelifblock.
- leading_lines: Sequence[EmptyLine]
Sequence of empty lines appearing before this compound statement line.
- whitespace_before_test: SimpleWhitespace
The whitespace appearing after the
ifkeyword but before the test expression.
- whitespace_after_test: SimpleWhitespace
The whitespace appearing after the test expression but before the colon.
- class libcst.Try[source]
A regular
trystatement that cannot containExceptStarblocks. Fortrystatements that can containExceptStarblocks, seeTryStar.- handlers: Sequence[ExceptHandler]
A list of zero or more exception handlers.
- leading_lines: Sequence[EmptyLine]
Sequence of empty lines appearing before this compound statement line.
- whitespace_before_colon: SimpleWhitespace
The whitespace that appears after the
trykeyword but before the colon.
- class libcst.While[source]
A
whilestatement.- test: BaseExpression
The test we will loop against.
- orelse: Else | None
An optional else case which will be executed if there is no
Breakstatement encountered while looping.
- whitespace_after_while: SimpleWhitespace
Whitespace after the
whilekeyword and before the test.
- whitespace_before_colon: SimpleWhitespace
Whitespace after the test and before the colon.
- class libcst.With[source]
A
withstatement.- asynchronous: Asynchronous | None
Optional async modifier if this is an
async withstatement.
- lpar: LeftParen | MaybeSentinel
Optional open parenthesis for multi-line with bindings
- rpar: RightParen | MaybeSentinel
Optional close parenthesis for multi-line with bindings
- whitespace_after_with: SimpleWhitespace
Whitespace after the
withkeyword and before the first item.
- whitespace_before_colon: SimpleWhitespace
Whitespace after the last item and before the colon.
Helper Nodes
Nodes that are used by various statements to represent some syntax, but are not statements on their own and cannot be used outside of the statements they belong with.
- class libcst.Annotation[source]
An annotation for a function (PEP 3107) or on a variable (PEP 526). Typically these are used in the context of type hints (PEP 484), such as:
# a variable with a type good_ideas: List[str] = [] # a function with type annotations def concat(substrings: Sequence[str]) -> str: ...
- annotation: BaseExpression
The annotation’s value itself. This is the part of the annotation after the colon or arrow.
- whitespace_before_indicator: BaseParenthesizableWhitespace | MaybeSentinel
- whitespace_after_indicator: BaseParenthesizableWhitespace
- class libcst.AsName[source]
An
as nameclause inside anExceptHandler,ImportAliasorWithItemnode.- whitespace_before_as: BaseParenthesizableWhitespace
Whitespace between the parent node and the
askeyword.
- whitespace_after_as: BaseParenthesizableWhitespace
Whitespace between the
askeyword and the name.
- class libcst.AssignTarget[source]
A target for an
Assign. Owns the equals sign and the whitespace around it.- target: BaseAssignTargetExpression
The target expression being assigned to.
- whitespace_before_equal: SimpleWhitespace
The whitespace appearing before the equals sign.
- whitespace_after_equal: SimpleWhitespace
The whitespace appearing after the equals sign.
- class libcst.BaseAssignTargetExpression[source]
An expression that’s valid on the left side of an assignment. That assignment may be part an
Assignnode, or it may be part of a number of other control structures that perform an assignment, such as aForloop.Python’s grammar defines all expression as valid in this position, but the AST compiler further restricts the allowed types, which is what this type attempts to express.
This is similar to a
BaseDelTargetExpression, but it also includesStarredElementas a valid node.The set of valid nodes are defined as part of CPython’s AST context computation.
- class libcst.BaseDelTargetExpression[source]
An expression that’s valid on the right side of a
Delstatement.Python’s grammar defines all expression as valid in this position, but the AST compiler further restricts the allowed types, which is what this type attempts to express.
This is similar to a
BaseAssignTargetExpression, but it excludesStarredElement.The set of valid nodes are defined as part of CPython’s AST context computation and as part of CPython’s bytecode compiler.
- class libcst.Decorator[source]
A single decorator that decorates a
FunctionDefor aClassDef.- decorator: BaseExpression
The decorator that will return a new function wrapping the parent of this decorator.
- leading_lines: Sequence[EmptyLine]
Line comments and empty lines before this decorator. The parent
FunctionDeforClassDefnode owns leading lines before the first decorator so that if the first decorator is removed, spacing is preserved.
- whitespace_after_at: SimpleWhitespace
Whitespace after the
@and before the decorator expression itself.
- trailing_whitespace: TrailingWhitespace
Optional trailing comment and newline following the decorator before the next line.
- class libcst.Else[source]
An
elseclause that appears optionally after anIf,While,Try, orForstatement.This node does not match
elifclauses inIfstatements. It also does not match the requiredelseclause in anIfExpexpression (a = if b else c).- leading_lines: Sequence[EmptyLine]
Sequence of empty lines appearing before this compound statement line.
- whitespace_before_colon: SimpleWhitespace
The whitespace appearing after the
elsekeyword but before the colon.
- class libcst.ExceptHandler[source]
An
exceptclause that appears optionally after aTrystatement.- type: BaseExpression | None
The type of exception this catches. Can be a tuple in some cases, or
Noneif the code is catching all exceptions.
- leading_lines: Sequence[EmptyLine]
Sequence of empty lines appearing before this compound statement line.
- whitespace_after_except: SimpleWhitespace
The whitespace between the
exceptkeyword and the type attribute.
- whitespace_before_colon: SimpleWhitespace
The whitespace after any type or name node (whichever comes last) and the colon.
- class libcst.Finally[source]
A
finallyclause that appears optionally after aTrystatement.- leading_lines: Sequence[EmptyLine]
Sequence of empty lines appearing before this compound statement line.
- whitespace_before_colon: SimpleWhitespace
The whitespace that appears after the
finallykeyword but before the colon.
- class libcst.ImportAlias[source]
An import, with an optional
AsName. Used in bothImportandImportFromto specify a single import out of another module.- comma: Comma | MaybeSentinel
Any trailing comma that appears after this import. This is optional for the last
ImportAliasin aImportorImportFrom, but all other import aliases inside an import must contain a comma to disambiguate multiple imports.
- property evaluated_name: str
Returns the string name this
ImportAliasrepresents.
- property evaluated_alias: str | None
Returns the string name for any alias that this
ImportAliashas. If there is noasnameattribute, this returnsNone.
- class libcst.NameItem[source]
A single identifier name inside a
GlobalorNonlocalstatement.This exists because a list of names in a
globalornonlocalstatement need to be separated by a comma, which ends up owned by theNameItemnode.
- class libcst.Parameters[source]
A function or lambda parameter list.
- params: Sequence[Param]
Positional parameters, with or without defaults. Positional parameters with defaults must all be after those without defaults.
- star_arg: Param | ParamStar | MaybeSentinel
- posonly_params: Sequence[Param]
Positional-only parameters, with or without defaults. Positional-only parameters with defaults must all be after those without defaults.
- posonly_ind: ParamSlash | MaybeSentinel
Optional sentinel that dictates parameters preceeding are positional-only args.
- class libcst.Param[source]
A positional or keyword argument in a
Parameterslist. May contain anAnnotationand, in some cases, adefault.- annotation: Annotation | None
Any optional
Annotation. These annotations are usually used as type hints.
- equal: AssignEqual | MaybeSentinel
The equal sign used to denote assignment if there is a default.
- default: BaseExpression | None
Any optional default value, used when the argument is not supplied.
- comma: Comma | MaybeSentinel
A trailing comma. If one is not provided,
MaybeSentinelwill be replaced with a comma only if a comma is required.
- star: str | MaybeSentinel
Zero, one, or two asterisks appearing before name for
Param’sstar_argandstar_kwarg.
- whitespace_after_star: BaseParenthesizableWhitespace
The whitespace before
name. It will appear afterstarwhen a star exists.
- whitespace_after_param: BaseParenthesizableWhitespace
The whitespace after this entire node.
- class libcst.ParamSlash[source]
A sentinel indicator on a
Parameterslist to denote that the previous params are positional-only args.This syntax is described in PEP 570.
- comma: Comma | MaybeSentinel
Optional comma that comes after the slash. This comma doesn’t own the whitespace between
/and,.
- whitespace_after: BaseParenthesizableWhitespace
Whitespace after the
/character. This is captured here in case there is a comma.
- class libcst.ParamStar[source]
A sentinel indicator on a
Parameterslist to denote that the subsequent params are keyword-only args.This syntax is described in PEP 3102.
- class libcst.WithItem[source]
A single context manager in a
Withblock, with an optional variable name.- item: BaseExpression
Expression that evaluates to a context manager.
- comma: Comma | MaybeSentinel
This is forbidden for the last
WithItemin aWith, but all other items inside a with block must contain a comma to separate them.
Statement Blocks
Nodes that represent some group of statements.
- class libcst.BaseSuite[source]
A dummy base-class for both
SimpleStatementSuiteandIndentedBlock. This exists to simplify type definitions and isinstance checks.A suite is a group of statements controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines.
- body: Sequence[BaseStatement] | Sequence[BaseSmallStatement]
- class libcst.SimpleStatementLine[source]
A simple statement that’s part of an IndentedBlock or Module. A simple statement is a series of small statements joined together by semicolons.
This isn’t differentiated from a
SimpleStatementSuitein the grammar, but because aSimpleStatementLinecan own additional whitespace that aSimpleStatementSuitedoesn’t have, we’re differentiating it in the CST.- body: Sequence[BaseSmallStatement]
Sequence of small statements. All but the last statement are required to have a semicolon.
- leading_lines: Sequence[EmptyLine]
Sequence of empty lines appearing before this simple statement line.
- trailing_whitespace: TrailingWhitespace
Any optional trailing comment and the final
NEWLINEat the end of the line.
- class libcst.SimpleStatementSuite[source]
A simple statement that’s used as a suite. A simple statement is a series of small statements joined together by semicolons. A suite is the thing that follows the colon in a compound statement.
if test:<leading_whitespace><body><trailing_whitespace>
This isn’t differentiated from a
SimpleStatementLinein the grammar, but because the two classes need to track different whitespace, we’re differentiating it in the CST.- body: Sequence[BaseSmallStatement]
Sequence of small statements. All but the last statement are required to have a semicolon.
- leading_whitespace: SimpleWhitespace
The whitespace between the colon in the parent statement and the body.
- trailing_whitespace: TrailingWhitespace
Any optional trailing comment and the final
NEWLINEat the end of the line.
- class libcst.IndentedBlock[source]
Represents a block of statements beginning with an
INDENTtoken and ending in aDEDENTtoken. Used as the body of compound statements, such as an if statement’s body.A common alternative to an
IndentedBlockis aSimpleStatementSuite, which can also be used as aBaseSuite, meaning that it can be used as the body of many compound statements.An
IndentedBlockalways occurs after a colon in aBaseCompoundStatement, so it owns the trailing whitespace for the compound statement’s clause.if test: # IndentedBlock's header body
- header: TrailingWhitespace
Any optional trailing comment and the final
NEWLINEat the end of the line.
- indent: str | None
A string represents a specific indentation. A
Nonevalue uses the modules’s default indentation. This is included because indentation is allowed to be inconsistent across a file, just not ambiguously.
Any trailing comments or lines after the dedent that are owned by this indented block. Statements own preceeding and same-line trailing comments, but not trailing lines, so it falls on
IndentedBlockto own it. In the case that a statement follows anIndentedBlock, that statement will own the comments and lines that are at the same indent as the statement, and thisIndentedBlockwill own the comments and lines that are indented further.
Operators
Nodes that are used to signify an operation to be performed on a variable or value.
Unary Operators
Nodes that are used with UnaryOperation to perform some unary
operation.
- class libcst.BitInvert
- class libcst.Minus
- class libcst.Not
- class libcst.Plus[source]
A unary operator that can be used in a
UnaryOperationexpression.- whitespace_after: BaseParenthesizableWhitespace
Any space that appears directly after this operator.
In addition, BaseUnaryOp is defined purely for typing and isinstance
checks.
- class libcst.BaseUnaryOp
Boolean Operators
Nodes that are used with BooleanOperation to perform some boolean
operation.
- class libcst.And
- class libcst.Or[source]
A boolean operator that can be used in a
BooleanOperationexpression.- whitespace_before: BaseParenthesizableWhitespace
Any space that appears directly before this operator.
- whitespace_after: BaseParenthesizableWhitespace
Any space that appears directly after this operator.
In addition, BaseBooleanOp is defined purely for typing and isinstance
checks.
- class libcst.BaseBooleanOp
Binary Operators
Nodes that are used with BinaryOperation to perform some binary
operation.
- class libcst.Add
- class libcst.BitAnd
- class libcst.BitOr
- class libcst.BitXor
- class libcst.Divide
- class libcst.FloorDivide
- class libcst.LeftShift
- class libcst.MatrixMultiply
- class libcst.Modulo
- class libcst.Multiply
- class libcst.Power
- class libcst.RightShift
- class libcst.Subtract[source]
A binary operator that can be used in a
BinaryOperationexpression.- whitespace_before: BaseParenthesizableWhitespace
Any space that appears directly before this operator.
- whitespace_after: BaseParenthesizableWhitespace
Any space that appears directly after this operator.
In addition, BaseBinaryOp is defined purely for typing and isinstance
checks.
- class libcst.BaseBinaryOp
Comparison Operators
Nodes that are used with Comparison to perform some comparison
operation.
- class libcst.Equal
- class libcst.GreaterThan
- class libcst.GreaterThanEqual
- class libcst.In
- class libcst.Is
- class libcst.LessThan
- class libcst.LessThanEqual[source]
A comparision operator that can be used in a
Comparisonexpression.- whitespace_before: BaseParenthesizableWhitespace
Any space that appears directly before this operator.
- whitespace_after: BaseParenthesizableWhitespace
Any space that appears directly after this operator.
- class libcst.NotEqual[source]
A comparison operator that can be used in a
Comparisonexpression.This node defines a static value for convenience, but in reality due to PEP 401 it can be one of two values, both of which should be a
NotEqualComparisonoperator.- whitespace_before: BaseParenthesizableWhitespace
Any space that appears directly before this operator.
- whitespace_after: BaseParenthesizableWhitespace
Any space that appears directly after this operator.
- class libcst.IsNot
- class libcst.NotIn[source]
A comparision operator that can be used in a
Comparisonexpression.This operator spans two tokens that must be separated by at least one space, so there is a third whitespace attribute to represent this.
- whitespace_before: BaseParenthesizableWhitespace
Any space that appears directly before this operator.
- whitespace_between: BaseParenthesizableWhitespace
Any space that appears between the
notandintokens.
- whitespace_after: BaseParenthesizableWhitespace
Any space that appears directly after this operator.
In addition, BaseCompOp is defined purely for typing and isinstance
checks.
- class libcst.BaseCompOp
Augmented Assignment Operators
Nodes that are used with AugAssign to perform some agumented
assignment.
- class libcst.AddAssign
- class libcst.BitAndAssign
- class libcst.BitOrAssign
- class libcst.BitXorAssign
- class libcst.DivideAssign
- class libcst.FloorDivideAssign
- class libcst.LeftShiftAssign
- class libcst.MatrixMultiplyAssign
- class libcst.ModuloAssign
- class libcst.MultiplyAssign
- class libcst.PowerAssign
- class libcst.RightShiftAssign
- class libcst.SubtractAssign[source]
An augmented assignment operator that can be used in a
AugAssignstatement.- whitespace_before: BaseParenthesizableWhitespace
Any space that appears directly before this operator.
- whitespace_after: BaseParenthesizableWhitespace
Any space that appears directly after this operator.
In addition, BaseAugOp is defined purely for typing and isinstance
checks.
- class libcst.BaseAugOp
Miscellaneous
Miscelaneous nodes that are purely syntactic trivia. While python requires these nodes in order to parse a module, statement or expression they do not carry any meaning on their own.
- class libcst.AssignEqual[source]
Used by
AnnAssignto denote a single equal character when doing an assignment on top of a type annotation. Also used byParamandArgto denote assignment of a default value, and byFormattedStringExpressionto denote usage of self-documenting expressions.- whitespace_before: BaseParenthesizableWhitespace
Any space that appears directly before this equal sign.
- whitespace_after: BaseParenthesizableWhitespace
Any space that appears directly after this equal sign.
- class libcst.Colon[source]
Used by
Sliceas a separator between subsequent expressions, and inLambdato separate arguments and body.- whitespace_before: BaseParenthesizableWhitespace
Any space that appears directly before this colon.
- whitespace_after: BaseParenthesizableWhitespace
Any space that appears directly after this colon.
- class libcst.Comma[source]
Syntactic trivia used as a separator between subsequent items in various parts of the grammar.
Some use-cases are:
ImportorImportFrom.FunctionDefarguments.
- whitespace_before: BaseParenthesizableWhitespace
Any space that appears directly before this comma.
- whitespace_after: BaseParenthesizableWhitespace
Any space that appears directly after this comma.
- class libcst.Dot[source]
Used by
Attributeas a separator between subsequentNamenodes.- whitespace_before: BaseParenthesizableWhitespace
Any space that appears directly before this dot.
- whitespace_after: BaseParenthesizableWhitespace
Any space that appears directly after this dot.
- class libcst.ImportStar[source]
Used by
ImportFromto denote a star import instead of a list of importable objects.
- class libcst.Semicolon[source]
Used by any small statement (any subclass of
BaseSmallStatementsuch asPass) as a separator between subsequent nodes contained within aSimpleStatementLineorSimpleStatementSuite.- whitespace_before: BaseParenthesizableWhitespace
Any space that appears directly before this semicolon.
- whitespace_after: BaseParenthesizableWhitespace
Any space that appears directly after this semicolon.
Whitespace
Nodes that encapsulate pure whitespace.
- class libcst.Comment[source]
A comment including the leading pound (
#) character.The leading pound character is included in the ‘value’ property (instead of being stripped) to help re-enforce the idea that whitespace immediately after the pound character may be significant. E.g:
# comment with whitespace at the start (usually preferred) #comment without whitespace at the start (usually not desirable)
Usually wrapped in a
TrailingWhitespaceorEmptyLinenode.
- class libcst.EmptyLine[source]
Represents a line with only whitespace/comments. Usually statements will own any
EmptyLinenodes above themselves, and aModulewill own the document’s header/footerEmptyLinenodes.- indent: bool
An empty line doesn’t have to correspond to the current indentation level. For example, this happens when all trailing whitespace is stripped and there is an empty line between two statements.
- whitespace: SimpleWhitespace
Extra whitespace after the indent, but before the comment.
- class libcst.Newline[source]
Represents the newline that ends an
EmptyLineor a statement (as part ofTrailingWhitespace).Other newlines may occur in the document after continuation characters (the backslash,
\), but those newlines are treated as part of theSimpleWhitespace.Optionally, a value can be specified in order to overwrite the module’s default newline. In general, this should be left as the default, which is
None. This is allowed because python modules are permitted to mix multiple unambiguous newline markers.
- class libcst.ParenthesizedWhitespace[source]
This is the kind of whitespace you might see inside a parenthesized expression or statement between two tokens when there is a newline without a line continuation (
\) character.https://docs.python.org/3/reference/lexical_analysis.html#implicit-line-joining
A parenthesized whitespace cannot be empty since it requires at least one
TrailingWhitespace. If you have whitespace that does not contain comments or newlines, useSimpleWhitespaceinstead.- first_line: TrailingWhitespace
The whitespace that comes after the previous node, up to and including the end-of-line comment and newline.
- empty_lines: Sequence[EmptyLine]
Any lines after the first that contain only indentation and/or comments.
- last_line: SimpleWhitespace
Extra whitespace after the indent, but before the next node.
- property empty: bool
Indicates that this node is empty (zero whitespace characters). For
ParenthesizedWhitespacethis will always beFalse.
- class libcst.SimpleWhitespace[source]
This is the kind of whitespace you might see inside the body of a statement or expression between two tokens. This is the most common type of whitespace.
A simple whitespace cannot contain a newline character unless it is directly preceeded by a line continuation character (
\). It can contain zero or more spaces or tabs. If you need a newline character without a line continuation character, useParenthesizedWhitespaceinstead.Simple whitespace is often non-semantic (optional), but in cases where whitespace solves a grammar ambiguity between tokens (e.g.
if test, versusiftest), it has some semantic value.An example
SimpleWhitespacecontaining a space, a line continuation, a newline and another space is as follows:SimpleWhitespace(r" \\n ")
- class libcst.TrailingWhitespace[source]
The whitespace at the end of a line after a statement. If a line contains only whitespace,
EmptyLineshould be used instead.- whitespace: SimpleWhitespace
Any simple whitespace before any comment or newline.
- class libcst.BaseParenthesizableWhitespace[source]
This is the kind of whitespace you might see inside the body of a statement or expression between two tokens. This is the most common type of whitespace.
The list of allowed characters in a whitespace depends on whether it is found inside a parenthesized expression or not. This class allows nodes which can be found inside or outside a
(),[]or{}section to accept either whitespace form.https://docs.python.org/3/reference/lexical_analysis.html#implicit-line-joining
Parenthesizable whitespace may contain a backslash character (
\), when used as a line-continuation character. While the continuation character isn’t technically “whitespace”, it serves the same purpose.Parenthesizable whitespace is often non-semantic (optional), but in cases where whitespace solves a grammar ambiguity between tokens (e.g.
if test, versusiftest), it has some semantic value.
Maybe Sentinel
- class libcst.MaybeSentinel[source]
A
MaybeSentinelvalue is used as the default value for some attributes to denote that when generating code (whenModule.codeis evaluated) we should optionally include this element in order to generate valid code.MaybeSentinelis only used for “syntactic trivia” that most users shouldn’t care much about anyways, like commas, semicolons, and whitespace.For example, a function call’s
Arg.commavalue defaults toMaybeSentinel.DEFAULT. A comma is required after every argument, except for the last one. If a comma is required andArg.commais aMaybeSentinel, one is inserted.This makes manual node construction easier, but it also means that we safely add arguments to a preexisting function call without manually fixing the commas:
>>> import libcst as cst >>> fn_call = cst.parse_expression("fn(1, 2)") >>> new_fn_call = fn_call.with_changes( ... args=[*fn_call.args, cst.Arg(cst.Integer("3"))] ... ) >>> dummy_module = cst.parse_module("") # we need to use Module.code_for_node >>> dummy_module.code_for_node(fn_call) 'fn(1, 2)' >>> dummy_module.code_for_node(new_fn_call) 'fn(1, 2, 3)'
Notice that a comma was automatically inserted after the second argument. Since the original second argument had no comma, it was initialized to
MaybeSentinel.DEFAULT. During the code generation of the second argument, a comma was inserted to ensure that the resulting code is valid.Warning
While this sentinel is used in place of nodes, it is not a
CSTNode, and will not be visited by aCSTVisitor.Some other libraries, like RedBaron, take other approaches to this problem. RedBaron’s tree is mutable (LibCST’s tree is immutable), and so they’re able to solve this problem with “proxy lists”. Both approaches come with different sets of tradeoffs.
- DEFAULT = 1