Skip to content

Initialization problems with preferunits for physical constants on Julia 1.8 #545

@j-fu

Description

@j-fu

Hi, I struggle with a subtle issue concerning the definition of physical constants in unitful.jl after preferunits has been set.

I set up a small package on https://github.com/j-fu/UTest.jl which can be dev'd for testing.

In the root directory it contains utest.jl which can be called either with

julia --project=. --compile=min utest.jl`

or with

julia --project=. utest.jl`

The correct output is

Unitful.upreferred(1 * u"m") = 100 cm
ustrip(upreferred(u"ε0")) = 8.85418781762039e-18
ustrip(upreferred(Unitful.ε0)) = 8.85418781762039e-18
ustrip(upreferred(PhysicalConstants.CODATA2018.ε_0)) = 8.8541878128e-18

This is obtained on all older Julia versions, and on 1.8 (beta, rc3) with --compile=min

On 1.8 (beta, rc3) and 1.9 (f1991edd30) without --compile=min one gets

Unitful.upreferred(1 * u"m") = 100 cm
ustrip(upreferred(u"ε0")) = 8.85418781762039e-12
ustrip(upreferred(Unitful.ε0)) = 8.85418781762039e-12
ustrip(upreferred(PhysicalConstants.CODATA2018.ε_0)) = 8.8541878128e-18

One gets the correct result with optimized code if after modification, the --compile=min has been called first. The problem occurs only for physical constants, not for units. PhysicalConstants.jl behaves in the right way, though.

I see three possibilities here:

  • Problem with the architecture of Unitful
  • Problem with code loading in Julia 1.8 when optimizing
  • Evaluating upreferred into the global context in a package using Unitful is a bad idea, even if preferunits is called before loading the package. If this is the case, it needs to be documented. (in fact I struggled with this situation in more obvious situations, so I have an Idea what to write into a PR...)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions