Type stability when DataType is passed as a keyword argument

Hi all-

I have a question about type stability when a DataType is passed as a keyword argument. The code below shows all combinations of positional vs keyword arguments and Float64 vs DataType. Why is the DataType keyword combination not type stable while the others are type stable? This holds true even with f(;T::DataType) = f(T).

Thank you

f(T::DataType) = Vector{T}(undef,1)

f(T::Float64) = T

f(;T) = f(T)

Here is a summary of the results:

# type stable

@code_warntype f(Int)

# type stable

@code_warntype f(.5)

# type stable

@code_warntype f(T=.5)

# not type stable

@code_warntype f(T=Int)

Keyword parameters do not participate in dispatch and functions do not specialize on them. The type of the returned value depend on T, therefore if the function takes T as a keyword argument without dispatching/specializing on it, it is not able to infer the type of the returned value without running the function, and this leads to type unstability. Also, there is no guarantee that your f with positional arguments will stay type-stable, I think inference may give up if you add 3 more methods for different types.


Thank you!

Note however that with “constant propagation” the compiler can still figure that last case out, its just that all of the code needs to be inside a function, e.g. this works:

@code_warntype (()->f(T=Int))()
1 Like