As an old C programmer, I use lots of asserts in my code. Now I want to globally switch them off to speed things up. What is the best practice way to do that?
Asked
Active
Viewed 1,308 times
2 Answers
14
There is no built-in option / command line flag to disable @assert
s globally, yet(!).
For now, you can define a @myassert
macro which, depending on a global switch, is a no-op or a regular @assert
:
asserting() = false # when set to true, this will enable all `@myassert`s
macro mayassert(test)
esc(:(if $(@__MODULE__).asserting()
@assert($test)
end))
end
f(x) = @mayassert x < 2
(taken from https://discourse.julialang.org/t/assert-alternatives/24775/14)

carstenbauer
- 9,817
- 1
- 27
- 40
3
You could put your @assert
statements in a @debug
block. Then the @assert
call is desactivated, unless you activate debugging either globally (ENV["JULIA_DEBUG"] = "all"
) or just for your module (ENV["JULIA_DEBUG"] = "NameOfYourModule"
)
julia> @debug begin
@assert 1==2
end
#or
@debug @assert 1==2 # assert is not called
julia> ENV["JULIA_DEBUG"] = "all" # enable debugging
"all"
julia> @debug begin
@assert 1==2
end
┌ Error: Exception while generating log record in module Main at REPL[4]:1
│ exception =
│ AssertionError: 1 == 2
│ Stacktrace:
│ [1] top-level scope at REPL[4]:2
│ [2] top-level scope at logging.jl:319
| ...
└ @ Main REPL[4]:1

Alex338207
- 1,825
- 12
- 16
-
Unfortunately, violation of the assertion no longer leads to program termination, but rather the log message `Error: Exception while generating log record in module`. – Jim Garrison Sep 10 '20 at 13:54