Loop through subtypes

In my package, I have a mother type T and subtypes T1,...,Tn that all must verify some conditions.

The conditions on these subtypes can easily be expressed as a test :

@test my_test_function(T1)
@test my_test_function(T2)
...

How can I loop through all subtypes of T ? Something like :

for Ti in subtypes(T)
    @test my_test_function(Ti)
end

The point is that I dont want to need to change the tests when adding a new one.

In what way is subtypes(T) insufficient?

Edit: I mean you already provided an implementation, no?

julia> abstract type Parent end

julia> struct T1 <: Parent end

julia> struct T2 <: Parent end

julia> has_feature(::Type{<:Parent}) = false
has_feature (generic function with 1 method)

julia> has_feature(::Type{T1}) = true
has_feature (generic function with 2 methods)

julia> for Ti in subtypes(Parent)
           @info Ti has_feature(Ti)
       end
┌ Info: T1
└   has_feature(Ti) = true
┌ Info: T2
└   has_feature(Ti) = false

3 Likes

In the way that I did not try subtypes before writing this message…

Thanks a lot, this is exactly what I need.

2 Likes