Stream: helpdesk (published)

Topic: `Symbol(::Type)` and `Symbol(::Module)`


view this post on Zulip Mason Protter (Jan 27 2021 at 00:26):

It was asked on #helpdesk earlier why one can do things like Symbol(Base) == :Base, and if it's appropriate to use this in metaprogramming.

view this post on Zulip Mason Protter (Jan 27 2021 at 00:26):

My answer was
Mason Protter said:

There's a method defined in base/strings/basic.jl which is

Symbol(x...) = Symbol(string(x...))

Hence, this should work for any values:

  string(xs...)

  Create a string from any values using the print function.

  string should usually not be defined directly. Instead, define a method print(io::IO, x::MyType). If string(x) for a certain
  type needs to be highly efficient, then it may make sense to add a method to string and define print(io::IO, x::MyType) =
  print(io, string(x)) to ensure the functions are consistent.

  Examples
  ≡≡≡≡≡≡≡≡≡≡

  julia> string("a", 1, true)
  "a1true"

It's documented in the manual that Symbol does this:

julia> @doc Symbol(x...)
  Symbol(x...) -> Symbol

  Create a Symbol by concatenating the string representations of the arguments together.

  Examples
  ≡≡≡≡≡≡≡≡≡≡

  julia> Symbol("my", "name")
  :myname

  julia> Symbol("day", 4)
  :day4

so, yes it is appropriate, safe and robust to use this.

I think however this was an error in earlier versions of Julia for nothing, so maybe be careful with that.


Last updated: Oct 02 2023 at 04:34 UTC