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¶ 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: Union[CSTTransformer, CSTVisitor]) → Union[_CSTNodeSelfT, libcst._removal_sentinel.RemovalSentinel][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: libcst._nodes.base.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: libcst._nodes.base.CSTNode, new_node: CSTNodeT) → Union[_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: libcst._nodes.base.CSTNode) → Union[_CSTNodeSelfT, libcst._removal_sentinel.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: libcst._nodes.base.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[Union[libcst._nodes.statement.SimpleStatementLine, libcst._nodes.statement.BaseCompoundStatement]]¶ A list of zero or more statements that make up this module.
-
header: Sequence[libcst._nodes.whitespace.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: Union[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¶ The string representation of this module, respecting the inferred indentation and newline type.
-
property
bytes¶ The bytes representation of this module, respecting the inferred indentation and newline type, using the current encoding.
-
code_for_node(node: libcst._nodes.base.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¶ 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)
-
get_docstring(clean: bool = True) → Optional[str][source]¶ Returns a
inspect.cleandoc()cleaned docstring if the docstring is available,Noneotherwise.
-
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.-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.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: libcst._nodes.expression.BaseExpression¶ An expression which, when evaluated, will produce an object with
attras an attribute.
-
attr: libcst._nodes.expression.Name¶ The name of the attribute being accessed on the
valueobject.
-
dot: libcst._nodes.op.Dot¶ A separating dot. If there’s whitespace between the
valueandattr, this dot owns it.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.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: libcst._nodes.op.BaseUnaryOp¶ The unary operator that applies some operation (e.g. negation) to the
expression.
-
expression: libcst._nodes.expression.BaseExpression¶ The expression that should be transformed (e.g. negated) by the operator to create a new value.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.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: libcst._nodes.expression.BaseExpression¶ The left hand side of the operation.
-
operator: libcst._nodes.op.BaseBinaryOp¶ The actual operator such as
<<or+that combines theleftandrightexpressions.
-
right: libcst._nodes.expression.BaseExpression¶ The right hand side of the operation.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.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: libcst._nodes.expression.BaseExpression¶ The left hand side of the operation.
-
operator: libcst._nodes.op.BaseBooleanOp¶ The actual operator such as
andororthat combines theleftandrightexpressions.
-
right: libcst._nodes.expression.BaseExpression¶ The right hand side of the operation.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.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: libcst._nodes.expression.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[libcst._nodes.expression.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.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.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: libcst._nodes.op.BaseCompOp¶ A comparison operator such as
<,>=,==,is, orin.
-
comparator: libcst._nodes.expression.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: libcst._nodes.whitespace.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: libcst._nodes.expression.BaseExpression¶ The actual expression we need to wait for.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.RightParen]¶ Sequence of parenthesis for precedence dictation.
-
whitespace_after_await: libcst._nodes.whitespace.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: Optional[Union[libcst._nodes.expression.BaseExpression, libcst._nodes.expression.From]]¶ The value yielded from the generator, in the case of a
Fromclause, a sub-generator to iterate over.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.RightParen]¶ Sequence of parenthesis for precedence dictation.
-
whitespace_after_yield: Union[libcst._nodes.whitespace.BaseParenthesizableWhitespace, libcst._maybe_sentinel.MaybeSentinel]¶ Whitespace after the
yieldkeyword, but before thevalue.
-
-
class
libcst.From[source]¶ A
from xstanza in aYieldorRaise.-
item: libcst._nodes.expression.BaseExpression¶ The expression that we are yielding/raising from.
-
whitespace_before_from: Union[libcst._nodes.whitespace.BaseParenthesizableWhitespace, libcst._maybe_sentinel.MaybeSentinel]¶ The whitespace at the very start of this node.
-
whitespace_after_from: libcst._nodes.whitespace.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: libcst._nodes.expression.BaseExpression¶ The test to perform.
-
body: libcst._nodes.expression.BaseExpression¶ The expression to evaluate when the test is true.
-
orelse: libcst._nodes.expression.BaseExpression¶ The expression to evaluate when the test is false.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.RightParen]¶ Sequence of parenthesis for precedence dictation.
-
whitespace_before_if: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Whitespace after the
bodyexpression, but before theifkeyword.
-
whitespace_after_if: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Whitespace after the
ifkeyword, but before thetestclause.
-
whitespace_before_else: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Whitespace after the
testexpression, but before theelsekeyword.
-
whitespace_after_else: libcst._nodes.whitespace.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: libcst._nodes.expression.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: libcst._nodes.expression.BaseExpression¶ The value that the lambda computes and returns when called.
-
colon: libcst._nodes.op.Colon¶ The colon separating the parameters from the body.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.RightParen]¶ Sequence of parenthesis for precedence dictation.
-
whitespace_after_lambda: Union[libcst._nodes.whitespace.BaseParenthesizableWhitespace, libcst._maybe_sentinel.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: libcst._nodes.expression.BaseExpression¶ The expression resulting in a callable that we are to call. Often a
NameorAttribute.
-
args: Sequence[libcst._nodes.expression.Arg]¶ The arguments to pass to the resulting callable. These may be a mix of positional arguments, keyword arguments, or “starred” arguments.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.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: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Whitespace after the
funcname, but before the opening parenthesis.
-
-
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: libcst._nodes.expression.BaseExpression¶ The argument expression itself, not including a preceding keyword, or any of the surrounding the value, like a comma or asterisks.
-
keyword: Optional[libcst._nodes.expression.Name]¶ Optional keyword for the argument.
-
equal: Union[libcst._nodes.op.AssignEqual, libcst._maybe_sentinel.MaybeSentinel]¶ The equal sign used to denote assignment if there is a keyword.
-
comma: Union[libcst._nodes.op.Comma, libcst._maybe_sentinel.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: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Whitespace after the
star(if it exists), but before thekeywordorvalue(if no keyword is provided).
-
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.-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.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.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.RightParen]¶ Sequence of parenthesis for precedence dictation.
-
property
evaluated_value¶ 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.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.RightParen]¶ Sequence of parenthesis for precedence dictation.
-
property
evaluated_value¶ 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.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.RightParen]¶ Sequence of parenthesis for precedence dictation.
-
property
evaluated_value¶ 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.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.RightParen]¶ Sequence of parenthesis for precidence dictation.
-
property
prefix¶ Returns the string’s prefix, if any exists. The prefix can be
r,u,b,brorrb.
-
property
quote¶ Returns the quotation used to denote the string. Can be either
',",'''or""".
-
property
raw_value¶ 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¶ 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: Union[libcst._nodes.expression.SimpleString, libcst._nodes.expression.FormattedString]¶ String on the left of the concatenation.
-
right: Union[libcst._nodes.expression.SimpleString, libcst._nodes.expression.FormattedString, libcst._nodes.expression.ConcatenatedString]¶ String on the right of the concatenation.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.RightParen]¶ Sequence of parenthesis for precidence dictation.
-
whitespace_between: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Whitespace between the
leftandrightsubstrings.
-
property
evaluated_value¶ 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[libcst._nodes.expression.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.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.RightParen]¶ Sequence of parenthesis for precidence dictation.
-
property
prefix¶ Returns the string’s prefix, if any exists. The prefix can be
f,fr, orrf.
-
property
quote¶ Returns the quotation used to denote the string. Can be either
',",'''or""".
-
-
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: libcst._nodes.expression.BaseExpression¶ The expression we will evaluate and render when generating the string.
-
format_spec: Optional[Sequence[libcst._nodes.expression.BaseFormattedStringContent]]¶ An optional format specifier following the format specification mini-language.
-
whitespace_before_expression: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Whitespace after the opening curly brace (
{), but before theexpression.
-
whitespace_after_expression: libcst._nodes.whitespace.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: Optional[libcst._nodes.op.AssignEqual]¶ 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[libcst._nodes.expression.BaseElement]¶ A sequence containing all the
ElementandStarredElementnodes in the tuple.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.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: libcst._nodes.expression.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({}),_field_type=None)¶
-
rbracket: libcst._nodes.expression.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({}),_field_type=None)¶ Brackets surrounding the list.
-
lpar: Sequence[libcst._nodes.expression.LeftParen] = ()¶
-
rpar: Sequence[libcst._nodes.expression.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[libcst._nodes.expression.BaseElement]¶ A sequence containing all the
ElementandStarredElementnodes in the list.
-
lbracket: libcst._nodes.expression.LeftSquareBracket¶
-
rbracket: libcst._nodes.expression.RightSquareBracket¶ Brackets surrounding the list.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.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[libcst._nodes.expression.BaseElement]¶ A sequence containing all the
ElementandStarredElementnodes in the set.
-
lbrace: libcst._nodes.expression.LeftCurlyBrace¶
-
rbrace: libcst._nodes.expression.RightCurlyBrace¶ Braces surrounding the set.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.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.
-
value: libcst._nodes.expression.BaseExpression¶
-
-
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: libcst._nodes.expression.BaseExpression¶
-
comma: Union[libcst._nodes.op.Comma, libcst._maybe_sentinel.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: libcst._nodes.expression.BaseExpression¶
-
comma: Union[libcst._nodes.op.Comma, libcst._maybe_sentinel.MaybeSentinel]¶ A trailing comma. By default, we’ll only insert a comma if one is required.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶ Parenthesis at the beginning of the node, before the leading asterisk.
-
rpar: Sequence[libcst._nodes.expression.RightParen]¶ Parentheses after the value, but before a comma (if there is one).
-
whitespace_before_value: libcst._nodes.whitespace.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[libcst._nodes.expression.BaseDictElement]¶
-
lbrace: libcst._nodes.expression.LeftCurlyBrace¶
-
rbrace: libcst._nodes.expression.RightCurlyBrace¶
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.RightParen]¶
-
Dictionary Elements¶
-
class
libcst.BaseDictElement[source]¶ An element of a literal dict. For elements of a list, tuple, or set, see BaseElement.
-
value: libcst._nodes.expression.BaseExpression¶
-
-
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: libcst._nodes.expression.BaseExpression¶
-
value: libcst._nodes.expression.BaseExpression¶
-
comma: Union[libcst._nodes.op.Comma, libcst._maybe_sentinel.MaybeSentinel]¶ A trailing comma. By default, we’ll only insert a comma if one is required.
-
whitespace_before_colon: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Whitespace after the key, but before the colon in
key : value.
-
whitespace_after_colon: libcst._nodes.whitespace.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: libcst._nodes.expression.BaseExpression¶
-
comma: Union[libcst._nodes.op.Comma, libcst._maybe_sentinel.MaybeSentinel]¶ A trailing comma. By default, we’ll only insert a comma if one is required.
-
whitespace_before_value: libcst._nodes.whitespace.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.-
for_in: libcst._nodes.expression.CompFor¶
-
-
class
libcst.BaseSimpleComp[source]¶ The base class for
ListComp,SetComp, andGeneratorExp.DictCompis not aBaseSimpleComp, because it useskeyandvalue.-
elt: libcst._nodes.expression.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: libcst._nodes.expression.BaseAssignTargetExpression¶ The expression evaluated and yielded during each iteration of the generator.
-
for_in: libcst._nodes.expression.CompFor¶ The
for ... in ... if ...clause that comes afterelt. This may be a nested structure for nested comprehensions. SeeCompForfor details.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
-
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: libcst._nodes.expression.BaseAssignTargetExpression¶ The expression evaluated and stored during each iteration of the comprehension.
-
for_in: libcst._nodes.expression.CompFor¶ The
for ... in ... if ...clause that comes afterelt. This may be a nested structure for nested comprehensions. SeeCompForfor details.
-
lbracket: libcst._nodes.expression.LeftSquareBracket¶
-
rbracket: libcst._nodes.expression.RightSquareBracket¶ Brackets surrounding the list comprehension.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.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: libcst._nodes.expression.BaseAssignTargetExpression¶ The expression evaluated and stored during each iteration of the comprehension.
-
for_in: libcst._nodes.expression.CompFor¶ The
for ... in ... if ...clause that comes afterelt. This may be a nested structure for nested comprehensions. SeeCompForfor details.
-
lbrace: libcst._nodes.expression.LeftCurlyBrace¶
-
rbrace: libcst._nodes.expression.RightCurlyBrace¶ Braces surrounding the set comprehension.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.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: libcst._nodes.expression.BaseAssignTargetExpression¶ The key inserted into the dictionary during each iteration of the comprehension.
-
value: libcst._nodes.expression.BaseAssignTargetExpression¶ The value associated with the
keyinserted into the dictionary during each iteration of the comprehension.
-
for_in: libcst._nodes.expression.CompFor¶ The
for ... in ... if ...clause that lexically comes afterkeyandvalue. This may be a nested structure for nested comprehensions. SeeCompForfor details.
-
lbrace: libcst._nodes.expression.LeftCurlyBrace¶
-
rbrace: libcst._nodes.expression.RightCurlyBrace¶ Braces surrounding the dict comprehension.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.RightParen]¶ Sequence of parenthesis for precedence dictation.
-
whitespace_before_colon: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Whitespace after the key, but before the colon in
key : value.
-
whitespace_after_colon: libcst._nodes.whitespace.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: libcst._nodes.expression.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: libcst._nodes.expression.BaseExpression¶ The value to iterate over. Every value in
iteris stored intarget.
-
ifs: Sequence[libcst._nodes.expression.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: Optional[libcst._nodes.expression.CompFor]¶ 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: Optional[libcst._nodes.expression.Asynchronous]¶ An optional async modifier that appears before the
forkeyword.
-
whitespace_before: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Whitespace that appears at the beginning of this node, before the
forandasynckeywords.
-
whitespace_after_for: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Whitespace appearing after the
forkeyword, but before thetarget.
-
whitespace_before_in: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Whitespace appearing after the
target, but before theinkeyword.
-
whitespace_after_in: libcst._nodes.whitespace.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: libcst._nodes.expression.BaseExpression¶ An expression to evaluate. When interpreted, Python will coerce it to a boolean.
-
whitespace_before: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Whitespace before the
ifkeyword.
-
whitespace_before_test: libcst._nodes.whitespace.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: libcst._nodes.expression.BaseExpression¶ The left-hand expression which, when evaluated, will be subscripted, such as
xinx[2].
-
slice: Sequence[libcst._nodes.expression.SubscriptElement]¶ The
SubscriptElementto extract from thevalue.
-
lbracket: libcst._nodes.expression.LeftSquareBracket¶
-
rbracket: libcst._nodes.expression.RightSquareBracket¶ Brackets after the
valuesurrounding theslice.
-
lpar: Sequence[libcst._nodes.expression.LeftParen]¶
-
rpar: Sequence[libcst._nodes.expression.RightParen]¶ Sequence of parenthesis for precedence dictation.
-
whitespace_after_value: libcst._nodes.whitespace.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: libcst._nodes.expression.BaseExpression¶ The index value itself.
-
-
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: Optional[libcst._nodes.expression.BaseExpression]¶ The lower bound in the slice, if present
-
upper: Optional[libcst._nodes.expression.BaseExpression]¶ The upper bound in the slice, if present
-
step: Optional[libcst._nodes.expression.BaseExpression]¶ The step in the slice, if present
-
first_colon: libcst._nodes.op.Colon¶ The first slice operator
-
second_colon: Union[libcst._nodes.op.Colon, libcst._maybe_sentinel.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.-
slice: libcst._nodes.expression.BaseSlice¶ A slice or index that is part of a subscript.
-
comma: Union[libcst._nodes.op.Comma, libcst._maybe_sentinel.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: libcst._nodes.whitespace.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: libcst._nodes.whitespace.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: libcst._nodes.whitespace.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: libcst._nodes.whitespace.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: libcst._nodes.whitespace.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: libcst._nodes.whitespace.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: Union[libcst._nodes.op.Semicolon, libcst._maybe_sentinel.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: libcst._nodes.expression.BaseAssignTargetExpression¶ The target that is being annotated and possibly assigned to.
-
annotation: libcst._nodes.expression.Annotation¶ The annotation for the target.
-
value: Optional[libcst._nodes.expression.BaseExpression]¶ The optional expression being assigned to the target.
-
equal: Union[libcst._nodes.op.AssignEqual, libcst._maybe_sentinel.MaybeSentinel]¶ The equals sign used to denote assignment if there is a value.
-
semicolon: Union[libcst._nodes.op.Semicolon, libcst._maybe_sentinel.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: libcst._nodes.expression.BaseExpression¶ The test we are going to assert on.
-
msg: Optional[libcst._nodes.expression.BaseExpression]¶ The optional message to display if the test evaluates to a falsey value.
-
comma: Union[libcst._nodes.op.Comma, libcst._maybe_sentinel.MaybeSentinel]¶ A comma separating test and message, if there is a message.
-
whitespace_after_assert: libcst._nodes.whitespace.SimpleWhitespace¶ Whitespace appearing after the
assertkeyword and before the test.
-
semicolon: Union[libcst._nodes.op.Semicolon, libcst._maybe_sentinel.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[libcst._nodes.statement.AssignTarget]¶ One or more targets that are being assigned to.
-
value: libcst._nodes.expression.BaseExpression¶ The expression being assigned to the targets.
-
semicolon: Union[libcst._nodes.op.Semicolon, libcst._maybe_sentinel.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: libcst._nodes.expression.BaseAssignTargetExpression¶ Target that is being operated on and assigned to.
-
operator: libcst._nodes.op.BaseAugOp¶ The augmented assignment operation being performed.
-
value: libcst._nodes.expression.BaseExpression¶ The value used with the above operator to calculate the new assignment.
-
semicolon: Union[libcst._nodes.op.Semicolon, libcst._maybe_sentinel.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: Union[libcst._nodes.op.Semicolon, libcst._maybe_sentinel.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: Union[libcst._nodes.op.Semicolon, libcst._maybe_sentinel.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: libcst._nodes.expression.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: libcst._nodes.whitespace.SimpleWhitespace¶ The whitespace after the
delkeyword.
-
semicolon: Union[libcst._nodes.op.Semicolon, libcst._maybe_sentinel.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: libcst._nodes.expression.BaseExpression¶ The expression itself. Python will evaluate the expression but not assign the result anywhere.
-
semicolon: Union[libcst._nodes.op.Semicolon, libcst._maybe_sentinel.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.-
names: Sequence[libcst._nodes.statement.NameItem]¶ A list of one or more names.
-
whitespace_after_global: libcst._nodes.whitespace.SimpleWhitespace¶ Whitespace appearing after the
globalkeyword and before the first name.
-
semicolon: Union[libcst._nodes.op.Semicolon, libcst._maybe_sentinel.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[libcst._nodes.statement.ImportAlias]¶ One or more names that are being imported, with optional local aliases.
-
semicolon: Union[libcst._nodes.op.Semicolon, libcst._maybe_sentinel.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: libcst._nodes.whitespace.SimpleWhitespace¶ The whitespace that appears after the
importkeyword but before the first import alias.
-
-
class
libcst.ImportFrom[source]¶ A
from x import ystatement.-
module: Optional[Union[libcst._nodes.expression.Attribute, libcst._nodes.expression.Name]]¶ Name or Attribute node representing the module we’re importing from. This is optional as
ImportFromallows purely relative imports.
-
names: Union[Sequence[libcst._nodes.statement.ImportAlias], libcst._nodes.op.ImportStar]¶ One or more names that are being imported from the specified module, with optional local aliases.
-
lpar: Optional[libcst._nodes.expression.LeftParen]¶ Optional open parenthesis for multi-line import continuation.
-
rpar: Optional[libcst._nodes.expression.RightParen]¶ Optional close parenthesis for multi-line import continuation.
-
semicolon: Union[libcst._nodes.op.Semicolon, libcst._maybe_sentinel.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: libcst._nodes.whitespace.SimpleWhitespace¶ The whitespace that appears after the
fromkeyword but before the module and any relative import dots.
-
whitespace_before_import: libcst._nodes.whitespace.SimpleWhitespace¶ The whitespace that appears after the module but before the
importkeyword.
-
whitespace_after_import: libcst._nodes.whitespace.SimpleWhitespace¶ The whitespace that appears after the
importkeyword but before the first import name or optional left paren.
-
-
class
libcst.Nonlocal[source]¶ A
nonlocalstatement.-
names: Sequence[libcst._nodes.statement.NameItem]¶ A list of one or more names.
-
whitespace_after_nonlocal: libcst._nodes.whitespace.SimpleWhitespace¶ Whitespace appearing after the
globalkeyword and before the first name.
-
semicolon: Union[libcst._nodes.op.Semicolon, libcst._maybe_sentinel.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: Union[libcst._nodes.op.Semicolon, libcst._maybe_sentinel.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: Optional[libcst._nodes.expression.BaseExpression]¶ The exception that we should raise.
-
cause: Optional[libcst._nodes.expression.From]¶ Optionally, a
from causeclause to allow us to raise an exception out of another exception’s context.
-
whitespace_after_raise: Union[libcst._nodes.whitespace.SimpleWhitespace, libcst._maybe_sentinel.MaybeSentinel]¶ Any whitespace appearing between the
raisekeyword and the exception.
-
semicolon: Union[libcst._nodes.op.Semicolon, libcst._maybe_sentinel.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: Optional[libcst._nodes.expression.BaseExpression]¶ The optional expression that will be evaluated and returned.
-
whitespace_after_return: Union[libcst._nodes.whitespace.SimpleWhitespace, libcst._maybe_sentinel.MaybeSentinel]¶ Optional whitespace after the
returnkeyword before the optional value expression.
-
semicolon: Union[libcst._nodes.op.Semicolon, libcst._maybe_sentinel.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.
-
body: libcst._nodes.statement.BaseSuite¶ The body of this compound statement.
-
leading_lines: Sequence[libcst._nodes.whitespace.EmptyLine]¶ Any empty lines or comments appearing before this statement.
-
-
class
libcst.ClassDef[source]¶ A class definition.
-
name: libcst._nodes.expression.Name¶ The class name.
-
body: libcst._nodes.statement.BaseSuite¶ The class body.
-
bases: Sequence[libcst._nodes.expression.Arg]¶ Sequence of base classes this class inherits from.
-
keywords: Sequence[libcst._nodes.expression.Arg]¶ Sequence of keywords, such as “metaclass”.
-
decorators: Sequence[libcst._nodes.statement.Decorator]¶ Sequence of decorators applied to this class.
-
lpar: Union[libcst._nodes.expression.LeftParen, libcst._maybe_sentinel.MaybeSentinel]¶ Optional open parenthesis used when there are bases or keywords.
-
rpar: Union[libcst._nodes.expression.RightParen, libcst._maybe_sentinel.MaybeSentinel]¶ Optional close parenthesis used when there are bases or keywords.
-
leading_lines: Sequence[libcst._nodes.whitespace.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[libcst._nodes.whitespace.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: libcst._nodes.whitespace.SimpleWhitespace¶ Whitespace after the
classkeyword and before the class name.
-
whitespace_after_name: libcst._nodes.whitespace.SimpleWhitespace¶ Whitespace after the class name and before the opening parenthesis for the bases and keywords.
-
whitespace_before_colon: libcst._nodes.whitespace.SimpleWhitespace¶ Whitespace after the closing parenthesis or class name and before the colon.
-
get_docstring(clean: bool = True) → Optional[str][source]¶ Returns a
inspect.cleandoc()cleaned docstring if the docstring is available,Noneotherwise.
-
-
class
libcst.For[source]¶ A
for target in iterstatement.-
target: libcst._nodes.expression.BaseAssignTargetExpression¶ The target of the iterator in the for statement.
-
iter: libcst._nodes.expression.BaseExpression¶ The iterable expression we will loop over.
-
body: libcst._nodes.statement.BaseSuite¶ The suite that is wrapped with this statement.
-
orelse: Optional[libcst._nodes.statement.Else]¶ An optional else case which will be executed if there is no
Breakstatement encountered while looping.
-
asynchronous: Optional[libcst._nodes.expression.Asynchronous]¶ Optional async modifier, if this is an async for statement.
-
leading_lines: Sequence[libcst._nodes.whitespace.EmptyLine]¶ Sequence of empty lines appearing before this for statement.
-
whitespace_after_for: libcst._nodes.whitespace.SimpleWhitespace¶ Whitespace after the
forkeyword and before the target.
-
whitespace_before_in: libcst._nodes.whitespace.SimpleWhitespace¶ Whitespace after the target and before the
inkeyword.
-
whitespace_after_in: libcst._nodes.whitespace.SimpleWhitespace¶ Whitespace after the
inkeyword and before the iter.
-
whitespace_before_colon: libcst._nodes.whitespace.SimpleWhitespace¶ Whitespace after the iter and before the colon.
-
-
class
libcst.FunctionDef[source]¶ A function definition.
-
name: libcst._nodes.expression.Name¶ The function name.
-
params: libcst._nodes.expression.Parameters¶ The function parameters. Present even if there are no params.
-
body: libcst._nodes.statement.BaseSuite¶ The function body.
-
decorators: Sequence[libcst._nodes.statement.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: Optional[libcst._nodes.expression.Annotation]¶ An optional return annotation, if the function is annotated.
-
asynchronous: Optional[libcst._nodes.expression.Asynchronous]¶ Optional async modifier, if this is an async function.
-
leading_lines: Sequence[libcst._nodes.whitespace.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[libcst._nodes.whitespace.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: libcst._nodes.whitespace.SimpleWhitespace¶ Whitespace after the
defkeyword and before the function name.
-
whitespace_after_name: libcst._nodes.whitespace.SimpleWhitespace¶ Whitespace after the function name and before the opening parenthesis for the parameters.
-
whitespace_before_params: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Whitespace after the opening parenthesis for the parameters but before the first param itself.
-
whitespace_before_colon: libcst._nodes.whitespace.SimpleWhitespace¶ Whitespace after the closing parenthesis or return annotation and before the colon.
-
get_docstring(clean: bool = True) → Optional[str][source]¶ When docstring is available, returns a
inspect.cleandoc()cleaned docstring. Otherwise, returnsNone.
-
-
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: libcst._nodes.expression.BaseExpression¶ The expression that, when evaluated, should give us a truthy/falsey value.
-
body: libcst._nodes.statement.BaseSuite¶ The body of this compound statement.
-
orelse: Optional[Union[libcst._nodes.statement.If, libcst._nodes.statement.Else]]¶ An optional
eliforelseclause.Ifsignifies anelifblock.Elsesignifies anelseblock.Nonesignifies noelseorelifblock.
-
leading_lines: Sequence[libcst._nodes.whitespace.EmptyLine]¶ Sequence of empty lines appearing before this compound statement line.
-
whitespace_before_test: libcst._nodes.whitespace.SimpleWhitespace¶ The whitespace appearing after the
ifkeyword but before the test expression.
-
whitespace_after_test: libcst._nodes.whitespace.SimpleWhitespace¶ The whitespace appearing after the test expression but before the colon.
-
-
class
libcst.Try[source]¶ A
trystatement.-
body: libcst._nodes.statement.BaseSuite¶ The suite that is wrapped with a try statement.
-
handlers: Sequence[libcst._nodes.statement.ExceptHandler]¶ A list of zero or more exception handlers.
-
orelse: Optional[libcst._nodes.statement.Else]¶ An optional else case.
-
finalbody: Optional[libcst._nodes.statement.Finally]¶ An optional finally case.
-
leading_lines: Sequence[libcst._nodes.whitespace.EmptyLine]¶ Sequence of empty lines appearing before this compound statement line.
-
whitespace_before_colon: libcst._nodes.whitespace.SimpleWhitespace¶ The whitespace that appears after the
trykeyword but before the colon.
-
-
class
libcst.While[source]¶ A
whilestatement.-
test: libcst._nodes.expression.BaseExpression¶ The test we will loop against.
-
body: libcst._nodes.statement.BaseSuite¶ The suite that is wrapped with this statement.
-
orelse: Optional[libcst._nodes.statement.Else]¶ An optional else case which will be executed if there is no
Breakstatement encountered while looping.
-
leading_lines: Sequence[libcst._nodes.whitespace.EmptyLine]¶ Sequence of empty lines appearing before this while statement.
-
whitespace_after_while: libcst._nodes.whitespace.SimpleWhitespace¶ Whitespace after the
whilekeyword and before the test.
-
whitespace_before_colon: libcst._nodes.whitespace.SimpleWhitespace¶ Whitespace after the test and before the colon.
-
-
class
libcst.With[source]¶ A
withstatement.-
items: Sequence[libcst._nodes.statement.WithItem]¶ A sequence of one or more items that evaluate to context managers.
-
body: libcst._nodes.statement.BaseSuite¶ The suite that is wrapped with this statement.
-
asynchronous: Optional[libcst._nodes.expression.Asynchronous]¶ Optional async modifier if this is an
async withstatement.
-
leading_lines: Sequence[libcst._nodes.whitespace.EmptyLine]¶ Sequence of empty lines appearing before this with statement.
-
whitespace_after_with: libcst._nodes.whitespace.SimpleWhitespace¶ Whitespace after the
withkeyword and before the first item.
-
whitespace_before_colon: libcst._nodes.whitespace.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: libcst._nodes.expression.BaseExpression¶ The annotation’s value itself. This is the part of the annotation after the colon or arrow.
-
whitespace_before_indicator: Union[libcst._nodes.whitespace.BaseParenthesizableWhitespace, libcst._maybe_sentinel.MaybeSentinel]¶
-
whitespace_after_indicator: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶
-
-
class
libcst.AsName[source]¶ An
as nameclause inside anExceptHandler,ImportAliasorWithItemnode.-
name: Union[libcst._nodes.expression.Name, libcst._nodes.expression.Tuple, libcst._nodes.expression.List]¶ Identifier that the parent node will be aliased to.
-
whitespace_before_as: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Whitespace between the parent node and the
askeyword.
-
whitespace_after_as: libcst._nodes.whitespace.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: libcst._nodes.expression.BaseAssignTargetExpression¶ The target expression being assigned to.
-
whitespace_before_equal: libcst._nodes.whitespace.SimpleWhitespace¶ The whitespace appearing before the equals sign.
-
whitespace_after_equal: libcst._nodes.whitespace.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: Union[libcst._nodes.expression.Name, libcst._nodes.expression.Attribute, libcst._nodes.expression.Call]¶ The decorator that will return a new function wrapping the parent of this decorator.
-
leading_lines: Sequence[libcst._nodes.whitespace.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: libcst._nodes.whitespace.SimpleWhitespace¶ Whitespace after the
@and before the decorator expression itself.
-
trailing_whitespace: libcst._nodes.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).-
body: libcst._nodes.statement.BaseSuite¶ The body of else clause.
-
leading_lines: Sequence[libcst._nodes.whitespace.EmptyLine]¶ Sequence of empty lines appearing before this compound statement line.
-
whitespace_before_colon: libcst._nodes.whitespace.SimpleWhitespace¶ The whitespace appearing after the
elsekeyword but before the colon.
-
-
class
libcst.ExceptHandler[source]¶ An
exceptclause that appears optionally after aTrystatement.-
body: libcst._nodes.statement.BaseSuite¶ The body of the except.
-
type: Optional[libcst._nodes.expression.BaseExpression]¶ The type of exception this catches. Can be a tuple in some cases, or
Noneif the code is catching all exceptions.
-
name: Optional[libcst._nodes.statement.AsName]¶ The optional name that a caught exception is assigned to.
-
leading_lines: Sequence[libcst._nodes.whitespace.EmptyLine]¶ Sequence of empty lines appearing before this compound statement line.
-
whitespace_after_except: libcst._nodes.whitespace.SimpleWhitespace¶ The whitespace between the
exceptkeyword and the type attribute.
-
whitespace_before_colon: libcst._nodes.whitespace.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.-
body: libcst._nodes.statement.BaseSuite¶ The body of the except.
-
leading_lines: Sequence[libcst._nodes.whitespace.EmptyLine]¶ Sequence of empty lines appearing before this compound statement line.
-
whitespace_before_colon: libcst._nodes.whitespace.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.-
name: Union[libcst._nodes.expression.Attribute, libcst._nodes.expression.Name]¶ Name or Attribute node representing the object we are importing.
-
asname: Optional[libcst._nodes.statement.AsName]¶ Local alias we will import the above object as.
-
comma: Union[libcst._nodes.op.Comma, libcst._maybe_sentinel.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¶ Returns the string name this
ImportAliasrepresents.
-
property
evaluated_alias¶ 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.-
name: libcst._nodes.expression.Name¶ Identifier name.
-
-
class
libcst.Parameters[source]¶ A function or lambda parameter list.
-
params: Sequence[libcst._nodes.expression.Param]¶ Positional parameters, with or without defaults. Positional parameters with defaults must all be after those without defaults.
-
star_arg: Union[libcst._nodes.expression.Param, libcst._nodes.expression.ParamStar, libcst._maybe_sentinel.MaybeSentinel]¶
-
kwonly_params: Sequence[libcst._nodes.expression.Param]¶ Keyword-only params that may or may not have defaults.
-
star_kwarg: Optional[libcst._nodes.expression.Param]¶ Optional parameter that captures unspecified kwargs.
-
posonly_params: Sequence[libcst._nodes.expression.Param]¶ Positional-only parameters, with or without defaults. Positional-only parameters with defaults must all be after those without defaults.
-
posonly_ind: Union[libcst._nodes.expression.ParamSlash, libcst._maybe_sentinel.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.-
name: libcst._nodes.expression.Name¶ The parameter name itself.
-
annotation: Optional[libcst._nodes.expression.Annotation]¶ Any optional
Annotation. These annotations are usually used as type hints.
-
equal: Union[libcst._nodes.op.AssignEqual, libcst._maybe_sentinel.MaybeSentinel]¶ The equal sign used to denote assignment if there is a default.
-
default: Optional[libcst._nodes.expression.BaseExpression]¶ Any optional default value, used when the argument is not supplied.
-
comma: Union[libcst._nodes.op.Comma, libcst._maybe_sentinel.MaybeSentinel]¶ A trailing comma. If one is not provided,
MaybeSentinelwill be replaced with a comma only if a comma is required.
-
star: Union[str, libcst._maybe_sentinel.MaybeSentinel]¶ Zero, one, or two asterisks appearing before name for
Param’sstar_argandstar_kwarg.
-
whitespace_after_star: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ The whitespace before
name. It will appear afterstarwhen a star exists.
-
whitespace_after_param: libcst._nodes.whitespace.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: Union[libcst._nodes.op.Comma, libcst._maybe_sentinel.MaybeSentinel]¶
-
-
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.
-
comma: libcst._nodes.op.Comma¶
-
-
class
libcst.WithItem[source]¶ A single context manager in a
Withblock, with an optional variable name.-
item: libcst._nodes.expression.BaseExpression¶ Expression that evaluates to a context manager.
-
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: Union[Sequence[libcst._nodes.statement.BaseStatement], Sequence[libcst._nodes.statement.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[libcst._nodes.statement.BaseSmallStatement]¶ Sequence of small statements. All but the last statement are required to have a semicolon.
-
leading_lines: Sequence[libcst._nodes.whitespace.EmptyLine]¶ Sequence of empty lines appearing before this simple statement line.
-
trailing_whitespace: libcst._nodes.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[libcst._nodes.statement.BaseSmallStatement]¶ Sequence of small statements. All but the last statement are required to have a semicolon.
-
leading_whitespace: libcst._nodes.whitespace.SimpleWhitespace¶ The whitespace between the colon in the parent statement and the body.
-
trailing_whitespace: libcst._nodes.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
-
body: Sequence[libcst._nodes.statement.BaseStatement]¶ Sequence of statements belonging to this indented block.
-
header: libcst._nodes.whitespace.TrailingWhitespace¶ Any optional trailing comment and the final
NEWLINEat the end of the line.
-
indent: Optional[str]¶ 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: libcst._nodes.whitespace.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: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Any space that appears directly before this operator.
-
whitespace_after: libcst._nodes.whitespace.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: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Any space that appears directly before this operator.
-
whitespace_after: libcst._nodes.whitespace.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: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Any space that appears directly before this operator.
-
whitespace_after: libcst._nodes.whitespace.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: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Any space that appears directly before this operator.
-
whitespace_after: libcst._nodes.whitespace.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: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Any space that appears directly before this operator.
-
whitespace_between: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Any space that appears between the
notandintokens.
-
whitespace_after: libcst._nodes.whitespace.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: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Any space that appears directly before this operator.
-
whitespace_after: libcst._nodes.whitespace.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: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Any space that appears directly before this equal sign.
-
whitespace_after: libcst._nodes.whitespace.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: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Any space that appears directly before this colon.
-
whitespace_after: libcst._nodes.whitespace.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: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Any space that appears directly before this comma.
-
whitespace_after: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Any space that appears directly after this comma.
-
class
libcst.Dot[source]¶ Used by
Attributeas a separator between subsequentNamenodes.-
whitespace_before: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Any space that appears directly before this dot.
-
whitespace_after: libcst._nodes.whitespace.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: libcst._nodes.whitespace.BaseParenthesizableWhitespace¶ Any space that appears directly before this semicolon.
-
whitespace_after: libcst._nodes.whitespace.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: libcst._nodes.whitespace.SimpleWhitespace¶ Extra whitespace after the indent, but before the comment.
-
comment: Optional[libcst._nodes.whitespace.Comment]¶ An optional comment appearing after the indent and extra whitespace.
-
newline: libcst._nodes.whitespace.Newline¶ The newline character that terminates this empty line.
-
-
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: libcst._nodes.whitespace.TrailingWhitespace¶ The whitespace that comes after the previous node, up to and including the end-of-line comment and newline.
-
empty_lines: Sequence[libcst._nodes.whitespace.EmptyLine]¶ Any lines after the first that contain only indentation and/or comments.
-
last_line: libcst._nodes.whitespace.SimpleWhitespace¶ Extra whitespace after the indent, but before the next node.
-
property
empty¶ 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 ")
-
value: str¶ Actual string value of the simple whitespace. A legal value contains only space,
\fand\tcharacters, and optionally a continuation (\) followed by a newline (\nor\r\n).
-
property
empty¶ Indicates that this node is empty (zero whitespace characters).
-
-
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: libcst._nodes.whitespace.SimpleWhitespace¶ Any simple whitespace before any comment or newline.
-
comment: Optional[libcst._nodes.whitespace.Comment]¶ An optional comment appearing after any simple whitespace.
-
newline: libcst._nodes.whitespace.Newline¶ The newline character that terminates this trailing whitespace.
-
-
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.-
abstract property
empty¶ Indicates that this node is empty (zero whitespace characters).
-
abstract property
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¶
-