How to change constant variable inside a package for testing

I am developing a new package. In package I have defined couple of constant variables. as it is not possible to redefine constant variable, I can’t change the constant variables for testing. we need to reset the Julia. I have an idea but it seems it is not a good way, using parallel processing to run all test files in parallel way. Note that I have defined those variables as constant to improve the performance.

Also I can use placeholder using Ref, but it is not as good as const. I am not sure whether the using const within a package is a good idea or not.

Something you can do is to replace constant variables with constant functions. For example:

const VERBOSE = false

function foo()
    if VERBOSE
        println("Hi!")
    end
end

becomes:

verbose() = false

function foo()
    if verbose()
        println("Hi!")
    end
end

Then in tests, you can redefine the function:

using MyPackage
MyPackage.verbose() = true
3 Likes

I would use a global Ref, unless it’s for something super performance sensitive. Looking up the value out of a Ref should be quite fast (assuming it is type stable, i.e. the Ref is concretely typed), and likely is not the bottleneck in most situations. It provides a simpler interface and does not require recompiling code to change the setting.

2 Likes

Thanks for sharing your idea. Nice trick.

Why not a typed global instead of a Ref?

verbose::Bool = false

?

3 Likes

This is what I am not sure about the performance about the typed global variable. but this link can help to explain about global variable issue.

To be honest, I have no idea about the performance of using global variable in package. We can define global paramters and wrap them into a function to improve the performance. I think we can consider the entire of package as a function.