Skip to content

Commit

Permalink
Merge pull request #160 from octoenergy/ranges-deepcopy
Browse files Browse the repository at this point in the history
Implement the copy and deepcopy protocol for Range
  • Loading branch information
jarshwah authored Jun 18, 2024
2 parents b80b295 + badf7b6 commit b86a601
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
30 changes: 30 additions & 0 deletions tests/test_ranges.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import copy
import datetime
import re
from typing import Any
Expand Down Expand Up @@ -966,6 +967,35 @@ def test_errors_if_infinite(self):
assert "Period is not finite at start or end or both" in str(exc_info.value)


class TestRangeCopy:
def test_range_copy(self):
r1 = ranges.Range(1, 2)
r2 = copy.copy(r1)
assert r1 == r2

def test_range_deepcopy(self):
r1 = ranges.Range(1, 2)
r2 = copy.deepcopy(r1)
assert r1 == r2

@pytest.mark.parametrize(
"obj",
[
ranges.Range(1, 2),
ranges.FiniteDateRange(
datetime.date(2000, 1, 1), datetime.date(2000, 1, 2)
),
ranges.FiniteDatetimeRange(
datetime.datetime(2000, 1, 1), datetime.datetime(2000, 1, 2)
),
ranges.HalfFiniteRange(1, 2),
],
ids=("range", "date_range", "datetime_range", "half_finite_range"),
)
def test_copies(self, obj):
assert obj == copy.copy(obj) == copy.deepcopy(obj)


def _rangeset_from_string(rangeset_str: str) -> ranges.RangeSet[int]:
"""
Convenience method to make test declarations clearer.
Expand Down
16 changes: 16 additions & 0 deletions xocto/ranges.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,22 @@ def __contains__(self, item: T) -> bool:
"""
return self._is_inside_left_bound(item) and self._is_inside_right_bound(item)

def __copy__(self) -> Range[T]:
"""
Return self.
Ranges are immutable, so there is no need to create a copy.
"""
return self

def __deepcopy__(self, memo: dict[Any, Any]) -> Range[T]:
"""
Return self.
Ranges are immutable, so there is no need to create a copy.
"""
return self

def _is_inside_left_bound(self, item: T) -> bool:
"""
Check if the provided item is inside our left bound.
Expand Down

0 comments on commit b86a601

Please sign in to comment.