Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/libcst/_flatten_sentinel.py: 69%
13 statements
« prev ^ index » next coverage.py v7.3.1, created at 2023-09-25 06:43 +0000
« prev ^ index » next coverage.py v7.3.1, created at 2023-09-25 06:43 +0000
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2#
3# This source code is licensed under the MIT license found in the
4# LICENSE file in the root directory of this source tree.
6import sys
8# PEP 585
9if sys.version_info < (3, 9):
10 from typing import Iterable, Sequence
11else:
12 from collections.abc import Iterable, Sequence
14from libcst._types import CSTNodeT_co
17class FlattenSentinel(Sequence[CSTNodeT_co]):
18 """
19 A :class:`FlattenSentinel` may be returned by a :meth:`CSTTransformer.on_leave`
20 method when one wants to replace a node with multiple nodes. The replaced
21 node must be contained in a `Sequence` attribute such as
22 :attr:`~libcst.Module.body`. This is generally the case for
23 :class:`~libcst.BaseStatement` and :class:`~libcst.BaseSmallStatement`.
24 For example to insert a print before every return::
26 def leave_Return(
27 self, original_node: cst.Return, updated_node: cst.Return
28 ) -> Union[cst.Return, cst.RemovalSentinel, cst.FlattenSentinel[cst.BaseSmallStatement]]:
29 log_stmt = cst.Expr(cst.parse_expression("print('returning')"))
30 return cst.FlattenSentinel([log_stmt, updated_node])
32 Returning an empty :class:`FlattenSentinel` is equivalent to returning
33 :attr:`cst.RemovalSentinel.REMOVE` and is subject to its requirements.
34 """
36 nodes: Sequence[CSTNodeT_co]
38 def __init__(self, nodes: Iterable[CSTNodeT_co]) -> None:
39 self.nodes = tuple(nodes)
41 def __getitem__(self, idx: int) -> CSTNodeT_co:
42 return self.nodes[idx]
44 def __len__(self) -> int:
45 return len(self.nodes)