Skip to content

Commit

Permalink
fix: backwards compatible dimensionless ranges
Browse files Browse the repository at this point in the history
  • Loading branch information
MilesCranmer committed Nov 20, 2024
1 parent 9ed7911 commit 8d7b2c5
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
7 changes: 5 additions & 2 deletions src/math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,11 @@ for T1 in (AbstractQuantity{<:Real}, Real),
end

if T3 === Real && !(T1 === T2 === Real)
@eval function Base.:(:)(::$T1, ::$T2)
error("When creating a range over quantities, you must specify a step.")
@eval function Base.:(:)(start::$T1, stop::$T2)
if !iszero(dimension(start)) || !iszero(dimension(stop))
error("When creating a range over dimensionful quantities, you must specify a step.")
end
return start:1:stop
end
end
end
Expand Down
7 changes: 5 additions & 2 deletions test/unittests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -371,8 +371,11 @@ end
# Test error for missing step
@test_throws "must specify a step" 1u"km":2u"km"
@test_throws "must specify a step" 1us"km":2us"km"
# Even for dimensionless, be explicit:
@test_throws "must specify a step" 1u"1":5u"1"

# However, for backwards compatibility, dimensionless ranges are allowed:
x = collect(1u"1":5u"1")
@test x == [1, 2, 3, 4, 5]
@test eltype(x) <: Quantity{Float64}

# Test errors for incompatible units
@test_throws DimensionError 1u"km":1u"s":5u"km"
Expand Down

0 comments on commit 8d7b2c5

Please sign in to comment.