@assert: what is the proper tool?

Apparently @assert can be elided by the compiler for some optimization level.
What is the recommended easy and fool-proof ways of asserting program behaviours?

if !(condition)
 error("error")
end

You can use @test too, but previous one is better.

using Test
@test condition

Yes, that is possible. But @assert condition "Try again!" is so much nicer.

macro myassert(ex, msgs...)
    msg = isempty(msgs) ? ex : msgs[1]
    if isa(msg, AbstractString)
        msg = msg # pass-through
    elseif !isempty(msgs) && (isa(msg, Expr) || isa(msg, Symbol))
        # message is an expression needing evaluating
        msg = :(Main.Base.string($(esc(msg))))
    elseif isdefined(Main, :Base) && isdefined(Main.Base, :string) && applicable(Main.Base.string, msg)
        msg = Main.Base.string(msg)
    else
        # string() might not be defined during bootstrap
        msg = quote
            msg = $(Expr(:quote,msg))
            isdefined(Main, :Base) ? Main.Base.string(msg) :
                (Core.println(msg); "Error during bootstrap. See stdout.")
        end
    end
    return :($(esc(ex)) ? $(nothing) : error($msg))
end
@myassert condition "try again!"
1 Like

Nice. But still: this means having to define this in all of your packages (or having one and using it).
Isn’t there something standard?

https://github.com/jw3126/ArgCheck.jl has @check macro

3 Likes