Count instances of type

Is it possible to ask Julia how many instances of an arbitrary type T are alive?

Assuming your “arbitrary type” T is a struct,
and it is ok with you to repeatedly use eval

symtype(x) = typeof(eval(x))
matchtype(T) = 
  filter(==(T), map(symtype, names(Main)))

function ninstances(::Type{T}) where {T}
    n = length(matchtype(T))
    return max(0, n-1)
end

struct A
   x::Int
end
julia> ninstances(A)
0
julia> a1 = A(1);  ninstances(A)
1
julia> a2= A(1);  ninstances(A)
2
1 Like

Do note, this won’t catch a3=[A(k) for k in 1:500]. You could write a function that also takes eltypes into account, but there will always be a way to “hide” an A. How about

struct B
    a::A
end
b = B(A(10))

If b.a should count as an instance of A then the answer to your question is probably “not without considerable effort”.

If you’re defining your own type and you just want to keep track of how many of that type you’ve spawned, can I suggest keeping a counter that is updated in the constructor and finalizer?