Anonymous function passed as a string gets overwritten

Hello julians,

I face a little puzzle in Julia that I can’t figure out. The code is straightforward:

function tada(period::Union{Nothing,Type{T}}=nothing) where {T<:Period})
    key = Vector{Function}()
    p = Symbol(period)
    while true
        println("p: $(p)")
        func = getfield(Dates, p)
        pushfirst!(key, x -> Dates.value(func(x)))
        up = Symbol(Dates.coarserperiod(func)[1])
        if (up == p)
            break
        else
            p = up
        end
    end
    println("First: $(key[1](Dates.now())). Second: $(key[2](Dates.now()))")
end

The idea is that the user can pass a Period as argument (say Dates.Month) and I want to get an array of functions that apply all the coarser periods.

The coarserperiod returns the “above” period. (ex: Dates.coarserperiod(Day) returns Dates.Week and Dates.coarserperiod(Month) returns Dates.Year).

The above code prints this:

> tada(Dates.Month)
> p: Month
> p: Year
> First: 2023. Second: 2023

as you can see, the loop does find the right coarser periods, but the function that are stored in the array are the same while they should not.

What am I missing?

I tried your code with various Julia versions, but I always get the answer you expect.

julia> function tada(period::Union{Nothing,Type{T}}=nothing) where {T<:Period}
           key = Vector{Function}()
           p = Symbol(period)
           while true
               println("p: $(p)")
               func = getfield(Dates, p)
               pushfirst!(key, x -> Dates.value(func(x)))
               up = Symbol(Dates.coarserperiod(func)[1])
               if (up == p)
                   break
               else
                   p = up
               end
           end
           println("First: $(key[1](Dates.now())). Second: $(key[2](Dates.now()))")
       end
tada (generic function with 2 methods)

julia> tada(Month)
p: Month
p: Year
First: 2023. Second: 4

So there must be something else, too, that messes up your environment.

Thank you @HanD. Hmm. I did spend some time debugging this! :sweat_smile:

I have no idea how to debug the environment. :confused:

But Thank you for looking into it. At least it’s not the code. :slight_smile:

1 Like

Restarted julia. It works :confused:

1 Like