Stream: helpdesk (published)

Topic: How to recover type programmatically?


view this post on Zulip Júlio Hoffimann (Dec 13 2021 at 23:20):

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

view this post on Zulip Mason Protter (Dec 13 2021 at 23:25):

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.

view this post on Zulip Sukera (Dec 13 2021 at 23:26):

I'm always wondering what context this occurs in

view this post on Zulip Sukera (Dec 13 2021 at 23:26):

always.

view this post on Zulip Mason Protter (Dec 13 2021 at 23:33):

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

view this post on Zulip Sukera (Dec 13 2021 at 23:34):

Notably, that wrapper is not always a valid constructor name

view this post on Zulip Mason Protter (Dec 13 2021 at 23:34):

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.

view this post on Zulip Júlio Hoffimann (Dec 13 2021 at 23:35):

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.

view this post on Zulip Sukera (Dec 13 2021 at 23:37):

sounds like you'd want to wrap those untrusted fields into their own struct and pass that as a configuration parameter

view this post on Zulip Sukera (Dec 13 2021 at 23:37):

but I'd guess we need more details/information to give proper help here

view this post on Zulip Eric Hanson (Dec 14 2021 at 15:35):

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

view this post on Zulip Alec (Dec 15 2021 at 04:12):

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