Suppose I have a parametric type:
struct Foo{T}
a::T
end
Foo(a, b) = Foo(a+b)
and an instance of this type:
foo = Foo(1, 2)
How do I retrieve the type Foo
from the instance foo
for future instantiations?
typeof(foo) # returns Foo{Int}, I just want Foo
This comes up about once a month or so, and the answer is that there is no officially supported way to do that without accessing undocumented language internals and that the Julia devs insist you shouldn't want to do it.
I'm always wondering what context this occurs in
always.
On current versions of julia, if you feel the need to do this, you can do this
julia> striptype(::Type{T}) where {T} = Base.typename(T).wrapper
striptype (generic function with 1 method)
julia> striptype(String)
String
julia> striptype(Vector{Int})
Array
julia> striptype(Array{String, 4})
Array
julia> striptype(Complex{Int})
Complex
But of course, these internals are subject to change
Notably, that wrapper is not always a valid constructor name
Often this comes up in the context of headaches with type promotion, and this seems like an easy way out. But yes, it is problematic.
The context here is that we have instances of structs for which only some fields are "trusted" or fine tuned by end users. We need to recover the type and some of the fields and then do some algorithmic work to fill in the remaining fields that are not ok yet.
sounds like you'd want to wrap those untrusted fields into their own struct and pass that as a configuration parameter
but I'd guess we need more details/information to give proper help here
If you don’t need it for all parametric types but just for a few, you could just write some methods like this, right?
unwrap(::Type{<:Foo}) = Foo
I essentially asked this on SO: https://stackoverflow.com/questions/70043313/get-simple-name-of-type-in-julia
Last updated: Nov 06 2024 at 04:40 UTC