How to write a unit test that checks whether a function is type stable

Amazing, something like Core.Compiler.return_type is what I actually needed.
I was not familiar with this feature, @Mason thanks for mentioning it!
Now I can do this:

@test !isa(return_type(type_unstable_function, Tuple{Int64, Int64}), Union)

Which should fail.
And these should pass

@test !isa(return_type(type_unstable_function, Tuple{Float64, Float64}), Union)
@test !isa(return_type(type_unstable_function, Tuple{Float64, Int64}), Union)

and they do.

EDIT

This does not cover the case return_type returns Any.
So some extension is needed for the above tests.
I’ll manage and thanks again!

EDIT 2
This would work for a function that can return a Union or an Any:

@test !any(x -> isa(return_type(type_unstable_function, Tuple{Int64, Int64}), x), (Union, Any))

and is extendible.

Also thanks for the warning.
It is good to know.

1 Like

I would instead just write isconcretetype(return_type(f, tt)). Your check for Union and Any will miss any abstract type between your type and Any.

1 Like

You’re right, I would have to keep on adding more stuff into the tuple of what to check for.
isconcretetype is excellent!