# Count instances of type

**URL:** <https://discourse.julialang.org/t/count-instances-of-type/70279>\
**Category:** General Usage\
**Created:** [October 24, 2021, 4:04am UTC](https://discourse.julialang.org/t/count-instances-of-type/70279 "2021-10-24T04:04:20Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jzr](https://avatars.discourse-cdn.com/v4/letter/j/eb9ed0/32.png) [@jzr](https://discourse.julialang.org/u/jzr)\
**Post date:** [October 24, 2021, 4:04am UTC](https://discourse.julialang.org/t/count-instances-of-type/70279/1 "2021-10-24T04:04:20Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![JeffreySarnoff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreysarnoff/32/1980_2.png) [@JeffreySarnoff](https://discourse.julialang.org/u/JeffreySarnoff)\
**Post date:** [October 24, 2021, 4:48am UTC](https://discourse.julialang.org/t/count-instances-of-type/70279/2 "2021-10-24T04:48:44Z")

</div>

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

```julia
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
julia> ninstances(A)
0
julia> a1 = A(1); ninstances(A)
1
julia> a2= A(1); ninstances(A)
2

```

---

<div class="post-metadata">

**Author:** ![gustaphe](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gustaphe/32/18174_2.png) [@gustaphe](https://discourse.julialang.org/u/gustaphe)\
**Post date:** [October 24, 2021, 6:03am UTC](https://discourse.julialang.org/t/count-instances-of-type/70279/3 "2021-10-24T06:03:45Z")

</div>

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

```julia
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?
