Skip to content

Let a VersionRange be open at either end - #371

Merged
Paebbels merged 4 commits into
devfrom
claude/version-range-open-bounds
Aug 31, 2026
Merged

Paebbels merged 4 commits into
devfrom
claude/version-range-open-bounds

Conversation

@pytooling-claude

Copy link
Copy Markdown

New Features

  • pyTooling.Versioning:
    • VersionRange accepts an open bound. Either lowerBound or upperBound may be None, leaving the range unbounded in that direction; a range open at both ends contains every version.
VersionRange(SemanticVersion.Parse("1.0.0"), None)   # 1.0.0 and everything above it
VersionRange(None, SemanticVersion.Parse("2.0.0"))   # everything up to 2.0.0
VersionRange(None, None)                             # every version

This is what Maven's and NuGet's [1.0,) needs, and it is what makes a single comparison such as >=1.0 expressible as a range at all — the missing half of the equivalence discussed on #369.

Changes

  • pyTooling.Versioning:
    • VersionRange._lowerBound and VersionRange._upperBound are Nullable[V], and VersionRange.LowerBound / VersionRange.UpperBound accept None to open a bound after construction.
    • VersionRange.__init__ skips the two checks that relate the bounds — compatible types, and lower not above upper — when either is missing, because neither question has an answer then. The per-bound type check is unchanged, so a non-Version bound is still rejected.
    • VersionRange.__contains__ does not make the comparison an open bound has nothing to compare against. RangeBoundHandling still applies to the bound that is present, so (1.0.0,) excludes 1.0.0 and admits everything above it.
    • VersionRange.__lt__, __le__, __gt__ and __ge__ answer False when the range is open in the direction being asked about — a range reaching past every version is never entirely below or above one. Their type check keys off whichever bound exists, and is skipped when the range is unbounded.
    • VersionRange.__and__ treats an open lower bound as the lowest of all and an open upper bound as the highest, so intersecting with an unbounded range returns the other one.

Nothing changes for a closed range: every existing bound combination, membership answer and intersection result is identical, which the existing tests/unit/Versioning/Range.py pins.

Bug Fixes

  • pyTooling.Versioning:
    • VersionRange.__and__'s exception notes were not commutative. A & B and B & A describe the same empty intersection, but the old implementation raised from a different branch depending on which operand was self, so the two notes carried different values. They now name the highest lower bound and the lowest upper bound, which is the same pair either way.

Known Issues

  • VersionRange.__and__ still drops BoundHandling — the intersection of two exclusive ranges is constructed with the default BothBoundsInclusive. That is pre-existing behaviour, unchanged here, and wants its own fix.
  • The four comparison operators now return bool(...) explicitly. Their type check compares against a dynamic class (reference.__class__), which widens other back to Any, so mypy types the comparison as Any. This was previously hidden because the attribute carried the type variable directly rather than an Optional of it.

Unit Tests

  • tests/unit/Versioning/Range.py:
    • A new OpenBounds class — 10 testcases over construction, membership with each bound open, bound handling on the present bound, the comparison operators, intersection, opening a bound afterwards, and that the closed-range checks still apply.
    • Intersection.test_DisjointIsCommutative — new, pinning that A & B and B & A produce identical notes.
    • Intersection.test_Disjoint_Reversed — updated. It asserted the old asymmetry; it now asserts the values the notes carry, with a comment saying why.

Whole suite: 1637 passed, 30 skipped, 3 xfailed. mypy on pyTooling/Versioning goes from 35 to 34 — removing a walrus operator in __init__, needed to wrap a line, fixed a pre-existing Incompatible types in assignment.

Others

Written up beforehand as T124 in the working notes, and split out of #369 deliberately: it changes VersionRange's public contract across eight methods, in code that PR does not otherwise touch.

Once this lands, #369 rebases onto it and can gain the rest of the unification discussed there:

  • VersionConstraint.ToVersionRange() for the five comparisons that are intervals — >=1.2.0 becomes [1.2.0, None), <2.0.0 becomes (None, 2.0.0), ==1.2.0 becomes [1.2.0, 1.2.0];
  • VersionExpression.ToVersionRange(), which is the intersection VersionRange.__and__ already computes.

!= remains the exception and will not convert: the complement of a point is not an interval but a union of two, so >=1.0,!=1.3,<2.0 — an ordinary requirement — has no single VersionRange. That is the reason both types stay, with the conversion as a bridge that can honestly fail.


Related Issues and Pull-Requests

@codacy-production

codacy-production Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 1 high · 4 minor

Alerts:
⚠ 5 issues (≤ 0 issues of at least minor severity)

Results:
5 new issues

Category Results
ErrorProne 1 high
CodeStyle 4 minor

View in Codacy

🟢 Metrics 0 duplication

Metric Results
Duplication 0

View in Codacy

🟢 Coverage 94.00% diff coverage · +0.21% coverage variation

Metric Results
Coverage variation ✅ +0.21% coverage variation
Diff coverage ✅ 94.00% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (35e06f5) 11153 9677 86.77%
Head commit (1d12cd2) 11193 (+40) 9735 (+58) 86.97% (+0.21%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#371) 100 94 94.00%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@codecov

codecov Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.00000% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 83.46%. Comparing base (35e06f5) to head (1d12cd2).
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
pyTooling/Versioning/__init__.py 89.00% 6 Missing and 5 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##              dev     #371      +/-   ##
==========================================
+ Coverage   83.23%   83.46%   +0.22%     
==========================================
  Files          51       51              
  Lines       11153    11193      +40     
  Branches     1696     1712      +16     
==========================================
+ Hits         9283     9342      +59     
+ Misses       1476     1458      -18     
+ Partials      394      393       -1     
Flag Coverage Δ
unittests 83.46% <89.00%> (+0.22%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

T124. A range needed both bounds, so Maven's '[1.0,)' - and a single
comparison like '>=1.0', which is the same thing - could not be expressed.
Either bound may be 'None' now, and a range open at both ends contains every
version.

* '_lowerBound' and '_upperBound' are 'Nullable[V]', and both properties
  accept 'None' to open the range afterwards.
* '__init__' skips the two checks that *relate* the bounds - compatible types,
  and lower not above upper - when either is missing, because neither
  question has an answer then. The per-bound type check still applies.
* '__contains__' simply doesn't make the comparison an open bound has nothing
  to compare against. 'RangeBoundHandling' still applies to the bound that is
  present, so '(1.0.0,)' excludes 1.0.0 and admits everything above it.
* '__lt__', '__le__', '__gt__' and '__ge__' answer 'False' when the range is
  open in the direction being asked about: a range reaching past every
  version is never entirely below or above one. Their type check keys off
  whichever bound exists, and is skipped when the range is unbounded.
* '__and__' treats an open lower bound as the lowest of all and an open upper
  bound as the highest, so intersecting with an unbounded range returns the
  other one.

Two things fell out that are worth naming:

'__and__' was rewritten as "highest lower bound, lowest upper bound", which
is the same result the branch-per-case version computed but is commutative.
The old notes were not: 'A & B' and 'B & A' described the same empty
intersection differently, because the raise came from a different branch.
'test_Disjoint_Reversed' asserted that asymmetry; it now asserts the values,
and a new 'test_DisjointIsCommutative' pins that both orders agree.

The four comparison operators return 'bool(...)' explicitly. Their type check
compares against a *dynamic* class ('reference.__class__'), which widens
'other' back to 'Any', so the comparison's type is 'Any' - previously hidden
because the attribute carried the type variable directly.

mypy on 'pyTooling/Versioning' goes from 35 to **34**: removing a walrus in
'__init__' fixed a pre-existing 'Incompatible types in assignment'.

tests/unit/Versioning/Range.py: 10 new testcases. Whole suite: 1637 passed.

Co-Authored-By: Patrick Lehmann <Paebbels@gmail.com>
@pytooling-claude
pytooling-claude Bot force-pushed the claude/version-range-open-bounds branch from 6f75a9e to 4f35960 Compare August 31, 2026 20:29
Comment thread pyTooling/Versioning/__init__.py Resolved
Comment thread pyTooling/Versioning/__init__.py Resolved
Comment thread pyTooling/Versioning/__init__.py Resolved
Comment thread pyTooling/Versioning/__init__.py Resolved
Comment thread pyTooling/Versioning/__init__.py Resolved
Comment thread pyTooling/Versioning/__init__.py Resolved
Comment thread pyTooling/Versioning/__init__.py Resolved
Comment thread pyTooling/Versioning/__init__.py Resolved
claude-code and others added 2 commits August 31, 2026 20:58
* "unbound" for a bound that is 'None', "open" for the range it leaves that
  way, throughout - both suggestions applied.
* The doc-block examples name the comparison each range stands for
  ('>=1.0.0', '<=2.0.0'), since whether the bound itself belongs to the range
  is 'RangeBoundHandling's business rather than the bound's.
* No parallel assignment, in either place.

**The bound setters now keep the invariant.** You were right that
reassignment could violate it, though not quite in the way described: neither
setter checked anything - the 'UpperBound' one did not either. On 'dev' this
is enough to build a range that contains nothing:

    r = VersionRange(v("1.0.0"), v("2.0.0"))
    r.LowerBound = v("5.0.0")     # accepted -> 5.0.0 .. 2.0.0
    v("1.5.0") in r               # False, and so is everything else

Both setters check it now, against the *other* bound and only when that bound
is present - with one end unbound there is no ordering to violate. Equal
bounds stay legal, as '__init__' already allows them.

**The 'bool()' wrappers are gone.** You are right that the comparison returns
a bool; what confused mypy was the type check on the line above, which
compares against a *dynamic* class ('reference.__class__') and so widened
'other' back to 'Any'. Binding the already-checked operand to a typed local
once - 'version: Version = other' - keeps the narrowing without a call, so
there is nothing left at runtime. mypy on 'pyTooling/Versioning' is at **34**,
one *below* the 35 on 'dev'.

tests/unit/Versioning/Range.py: 5 testcases for the invariant, including that
unbounding either end stays allowed. Whole suite: 1667 passed.

Co-Authored-By: Patrick Lehmann <Paebbels@gmail.com>
The three ways a version reaches a range disagreed about which types relate,
and all three predate this PR:

  bounds via __init__     Semantic + Python -> accepted (subclass)
  comparison operators    Semantic vs Python -> TypeError
  __contains__            Semantic vs Python -> accepted, unchecked
                          Semantic vs Calendar -> TypeError from Version.__le__

So a range refused to *compare* against a version it would happily have
accepted as one of its own bounds, and membership refused a sibling type with
an error raised four frames down - "Supported types for second operand:
SemanticVersion, VersionRange, VersionSet, str, int" - rather than a
deliberate one.

'_CheckCompatibility' is now that rule, in one place, and it is '__init__''s:
the same class, or one deriving from the other. The four comparison operators
and '__contains__' all call it. A range with both ends unbound carries no
bound type, so it relates to any version.

The operators used 'isinstance(a, type(b)) and isinstance(b, type(a))', a
*mutual* test that effectively demands the same class - strictly narrower than
what '__init__' permits, which is where the disagreement came from. It is
'issubclass' in either direction now, matching the constructor.

That also removes the mypy workaround entirely. The narrowing was being lost
to 'isinstance(other, reference.__class__)': an 'isinstance' against a
non-literal class re-narrows the operand, and since 'other' is declared 'Any'
there is nothing to narrow *to*, so it reverted to 'Any'. Bisected -

  both isinstance calls, no local          6x "Returning Any"
  only isinstance(reference, other.__class__)   0
  no dynamic isinstance at all                  0

- and with no 'isinstance' on 'other' left, neither the 'bool()' wrappers nor
the 'version: Version = other' binding are needed. Both are gone.

tests/unit/Versioning/Range.py: 6 testcases pinning that all three paths
accept a subclass, refuse a sibling, and that an unbound range relates to
anything. Whole suite: 1673 passed. mypy on 'pyTooling/Versioning' is at 34,
one below the 35 on 'dev'; CheckRaises unchanged at 40.

Co-Authored-By: Patrick Lehmann <Paebbels@gmail.com>
@pytooling-claude

Copy link
Copy Markdown
Author

f48604e — both done, and confirming your reading of __init__ first: it is same class, or one derives from the other. SemanticVersion + PythonVersion is accepted because PythonVersion derives from it; SemanticVersion + CalendarVersion is refused because they are siblings under Version. (CalendarVersion + YearMonthVersion is accepted for the same reason as the first.)

The three paths disagreed — all three before this PR

Semantic vs Python Semantic vs Calendar
bounds via __init__ accepted TypeError, deliberate
comparison operators TypeError TypeError, deliberate
__contains__ accepted, unchecked TypeError from Version.__le__

So a range refused to compare against a version it would happily have taken as one of its own bounds; and membership rejected a sibling four frames down with "Supported types for second operand: SemanticVersion, VersionRange, VersionSet, str, int" rather than a deliberate error.

The cause of the first row: the operators used isinstance(a, type(b)) and isinstance(b, type(a)), a mutual test that effectively demands the same class — strictly narrower than what __init__ permits.

Now

_CheckCompatibility holds the rule once, and it is __init__'s. The four comparison operators and __contains__ all call it. A range with both ends unbound carries no bound type, so it relates to any version.

It also removed the mypy workaround entirely

You asked why the typed local was needed at all, given the isinstance(other, Version) guard above. It was needed because the narrowing was being undone: an isinstance against a non-literal class re-narrows the operand, and since other is declared Any there is nothing to narrow to, so it reverted to Any. Bisected:

variant Returning Any
both isinstance calls, no local 6
only isinstance(reference, other.__class__) 0
no dynamic isinstance at all 0

With the check expressed as issubclass on the two classes, there is no isinstance on other left — so neither the bool() wrappers nor the local remain. mypy is at 34, one below dev's 35, with no workaround of any kind.

Six testcases pin that all three paths accept a subclass, refuse a sibling, and that an unbound range relates to anything. Whole suite 1673 passed; CheckRaises unchanged at 40.

One thing to be aware of: __contains__ now raises on a sibling type where it previously raised from deeper down, so the exception type is the same but the message and origin change. Nothing in the suite depended on the old text.

Fair point - '_CheckCompatibility' held the rule, but '__init__' still had its
own copy of the same boolean expression, written with different variable
names. And the two bound setters had a third and fourth copy, in the worst
form: neither checked the types at all, so assigning a sibling-typed bound
failed from inside 'Version.__le__' during the *ordering* check -

    r.LowerBound = CalendarVersion.Parse("2024.10")
    TypeError: Second operand is not supported by <= operator.

- which is the same deep, unhelpful error '__contains__' gave before this PR.

'_AreCompatible(left, right)' is the rule now, once, as a static predicate:
same class, or one deriving from the other. Four callers, each keeping its
own message:

* '__init__'            - the two bounds against each other;
* '_CheckCompatibility' - a version against whichever bound is present;
* 'LowerBound' setter   - the assigned value against the upper bound;
* 'UpperBound' setter   - the assigned value against the lower bound.

The setters check it *before* their ordering check, so an unrelated type now
fails deliberately and says which two types it saw. With the other end
unbound there is nothing to relate to, so any version is admissible there.

The setters also got 'ex' for their 'TypeError' and 'error' for their
'ValueError'; reusing one name for both re-types the variable and mypy
reports it, the same way it did in #369.

tests/unit/Versioning/Range.py: 2 more testcases. Whole suite: 1675 passed.
mypy on 'pyTooling/Versioning' is at 34, one below the 35 on 'dev'.

Co-Authored-By: Patrick Lehmann <Paebbels@gmail.com>
@Paebbels
Paebbels merged commit 05e4487 into dev Aug 31, 2026
64 of 65 checks passed
@Paebbels
Paebbels deleted the claude/version-range-open-bounds branch August 31, 2026 22:26
@pytooling-claude pytooling-claude Bot added bug Something isn't working Feature Request Unit Tests Versioning pyTooling.Versioning - Version numbers. labels Sep 6, 2026
@pytooling-claude pytooling-claude Bot added this to the v10.0 milestone Sep 6, 2026
This was referenced Oct 12, 2026
This was referenced Oct 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working Feature Request Unit Tests Versioning pyTooling.Versioning - Version numbers.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants