Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CodeRange.__contains__ #7

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions libcst/_position.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,14 @@ def __init__(self, start: _CodePositionT, end: _CodePositionT) -> None:
end = cast(CodePosition, end)
object.__setattr__(self, "start", start)
object.__setattr__(self, "end", end)

def __contains__(self, pos: _CodePositionT, /) -> bool:
if isinstance(pos, tuple):
line, column = pos
else:
line, column = pos.line, pos.column

return (
self.start.line <= line <= self.end.line
and self.start.column <= column <= self.end.column
)
29 changes: 29 additions & 0 deletions libcst/tests/test_position.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

from libcst._position import _CodePositionT, CodePosition, CodeRange
from libcst.testing.utils import data_provider, UnitTest


code_range = CodeRange((1, 2), (4, 5))


class PositionTest(UnitTest):
@data_provider(
[
(CodePosition(1, 2), True),
((1, 2), True),
(CodePosition(3, 3), True),
((3, 3), True),
(CodePosition(2, 1), False),
((2, 1), True),
(CodePosition(5, 4), False),
((5, 4), False),
]
)
def test_code_range_contains(
self, position: _CodePositionT, expected: bool
) -> None:
self.assertEqual(position in code_range, expected)