Unitful.jl: typeof() vs manually given types

Taking typeof() of some quantity, vs copy+pasting the output as a type definition โ€“ these two donโ€™t seem to be equivalent:

> typeof(1.0s)
Quantity{Float64, ๐“, Unitful.FreeUnits{(s,), ๐“, nothing}}

> 1.0s isa typeof(1.0s)
true

> 1.0s isa Quantity{Float64, ๐“, Unitful.FreeUnits{(s,), ๐“, nothing}}
false

Whatโ€™s my mistake here?

Loads of people must have asked this, but I couldnโ€™t find the answerโ€ฆ :disappointed_relieved:

1 Like
julia> typeof(1.0s)==
  Quantity{
    Float64, 
    Unitful.๐“, 
    Unitful.FreeUnits{
      (Unitful.Unit{:Second, Unitful.๐“}(0,1),), 
      Unitful.๐“, 
      nothing
    }
  }
true

The problem seems to be a mis-match between the way 1.0sโ€™s type is displayed and the type obtained by typing it as a literal. Specifically, s is Unitful.Unit{:Second, Unitful.๐“}(0,1) and not a another FreeUnits type (note that Unitful.s is a Unitful.FreeUnits{(s,), ๐“, nothing} type and thus just typing s or Unitful.s will not get the parameter of typeof(1.0s) right)

1 Like
julia> 1.0s isa Quantity{Float64, ๐“ , Unitful.FreeUnits{(Unitful.Unit{:Second, ๐“}(0, 1//1),), ๐“ , nothing}}
true

The culprit here is are overloads of show in Unitful

function show(io::IO, x::Unit{N,D}) where {N,D}
    show(io, FreeUnits{(x,), D, nothing}())
end

in conjunction with

function show(io::IO, x::Unitlike)
    showoperators = get(io, :showoperators, false)
    first = ""
    sep = showoperators ? "*" : " "
    foreach(sortexp(typeof(x).parameters[1])) do y
        print(io,first)
        showrep(io,y)
        first = sep
    end
    nothing
end

which will make Unitful.Unit{:Second, ๐“}(0, 1//1) print as s.

Question is, why are you comparing types this way? Iโ€™d imagine itโ€™d be more robust to check unit and dimension. But then again, isnโ€™t a major point of working with units needing not to care about units?

3 Likes

@Dan , @skleinbo: Thanks! :+1:

Iโ€™ve found Julia types can get very long, especially when using Unitful.jl. There seems to be two things competing: having the information from show be accurate (you can copy-paste it and get the same quantity) and having it show something readable and informative. I donโ€™t know what the best solution is, but Iโ€™ve gotten some truly nightmarish types when combining AxisArrays and Unitful.

2 Likes