Reputation: 384
Let's say I have the Union
:
SomeUnion = Union{Int, String}
Is there a method to extract a collection of types that form this union? For example ....
union_types(SomeUnion) # => [Int, String]
Upvotes: 7
Views: 976
Reputation: 2509
Base.uniontypes
is not documented (as of julia-1.6.1
), so use with care.
But it works:
julia> SomeUnion = Union{Int, String}
Union{Int64, String}
julia> Base.uniontypes(SomeUnion)
2-element Vector{Any}:
Int64
String
Upvotes: 2
Reputation: 2096
For Julia 0.6, NEWS.md states that "Union
types have two fields, a
and b
, instead of a single types
field". Additionally, "Parametric types with "unspecified" parameters, such as Array
, are now represented as UnionAll
types instead of DataType
s".
Thus, to get the types as a tuple, one can do
union_types(x::Union) = (x.a, union_types(x.b)...)
union_types(x::Type) = (x,)
If you want an array, just collect
the tuple
julia> collect(union_types(Union{Int, Float64, String, Array}))
4-element Array{Type,1}:
Int64
Float64
String
Array
Upvotes: 4
Reputation: 8566
just write down a simple example here:
a = Union(Int,String)
function union_types(x)
return x.types
end
julia> union_types(a)
(Int64,String)
you can store the result into an array if you want:
function union_types(x)
return collect(DataType, x.types)
end
julia> union_types(a)
2-element Array{DataType,1}:
Int64
String
UPDATE: use collect
as @Luc Danton suggested in comment below.
Upvotes: 3