Including a variable outside a function in a log message

Assume I have a function that does some calculation on a piece of data and I want to log when somewthing goes wrong:

struct MyData
    id::String
    number::Number
end

function main()

    data = [MyData("a", -1), MyData("b", 1)]

    for case in data
        id = case.id
        num = case.number
        
        my_calculation(num)
    end
    
end

function my_calculation(x::Number)

    if x < 0
        @warn "$(x) is smaller than zero!"
        return NaN
    end

    return sqrt(x)
end


main()

Can I somehow include the id of the data for which the calculation in the log message, without passing id as an argument to my_calculation? It seems “wrong” to do that since the calculation itself has nothing to do with the id.

No. If my_calculation isn’t given case.id somehow then it just has no access. If you can’t change that, you could @warn in main instead; you just need my_calculation to indicate something went wrong, like returning an indicator output (NaN, nothing) for main to check (isnan, isnothing) or throwing an error for main to handle (try catch finally).

2 Likes