Reflection API for Union types

Are there any methods to inspect Union types?

Ex:

julia> y::Union{Number,Nothing} = nothing

julia> typeof(y)
Nothing

1/ how to find out the fact that y is a Union?

2/ how to get the types supported by the Union (Number and Nothing)?

1 Like

Answer to 2) is Base.uniontypes though that isn’t exported

julia> Base.uniontypes(Union{Int, Nothing})
2-element Vector{Any}:
 Nothing
 Int64

You can find answers to a lot of questions about reflection in the ExprTools.jl package, in src/methods.jl because in the past i worked them out

1 Like

While uniontypes is not exported, it is only 3 lines long. I just copied it when I needed it

_uniontypes(x::Union, ts) = (_uniontypes(x.a,ts); _uniontypes(x.b,ts); ts)
_uniontypes(@nospecialize(x), ts) = (push!(ts, x); ts)
uniontypes(@nospecialize(x)) = _uniontypes(x, Any[])

This is really cool, thanks for sharing! Though I’m now wary of using unexported methods as them and the APIs they rely on can be removed in minor Julia versions (I’ve been bitten by this quite a few times already).

y isn’t a Union. Values don’t have non-concrete types.

5 Likes

That’s why I copy/pasted the code into my own project, then it will always be there

1 Like

Yes - that’s a very important point about Unions.

Or any abstract type :slight_smile: