Redefining a method used in a generated function

I understand that generated functions are generated “on demand” and therefore all used methods have to be defined before:

julia> @generated g() = (@show f(1); nothing)
g (generic function with 1 method)

julia> f(x) = x
f (generic function with 1 method)

julia> g()
ERROR: MethodError: no method matching f(::Int64)

However, why it is not possible to redefine methods like this?

julia> f(x) = x
f (generic function with 1 method)

julia> @generated g() = (@show f(1); nothing)
g (generic function with 1 method)

julia> f(x) = x-1
f (generic function with 1 method)

julia> g()
f(1) = 1

Is there a way around this or is it just fundamentally impossible? I am writing a library, where I would like to generate functions based on type traits and this would really come handy.

No, this is not safe. Although, it often works, there are no guarantees. Some discussion here: https://github.com/mauro3/SimpleTraits.jl/issues/40

1 Like

It is garanteed to not work. If it does then it’s a bug.

2 Likes