Given a function object, how do I find its name and module?

@oxinabox's answer is correct. To add, typeof(f).name.mt.name is the v0.5 replacement for f.env.name. That can be useful to avoid the . that occurs when just applying string to a function introduced in a non-stdlib module. There also exists Base.function_name(f) which is probably less likely to break when the Julia version changes.

To get the module that a function (type) is introduced in, rather than the modules of individual methods, there's typeof(f).name.module, or the probably-better version, Base.function_module(f). The module of the method table is probably the same; that can be obtained through typeof(f).name.mt.module.

Note that f.env in v0.4 is a direct equivalent of typeof(f).name.mt, so on v0.4 the same f.env.name and f.env.module apply.


Name is easy: Symbol(f) or string(f) if you want a string

Module is, as you know going to be per method (i.e per type signature). methods(f) with return a method table that prints out all the methods and where they are, in terms of files.

You can do [meth.module for meth in methods(f)] to get there modules

So to use an example, the collect function.

julia> using DataStructures #so we have some non-Base definitions

julia> Symbol(collect)
:collect

julia> methods(collect)
# 5 methods for generic function "collect":
collect(r::Range) at range.jl:813
collect{T}(::Type{T}, itr) at array.jl:211
collect(itr::Base.Generator) at array.jl:265
collect{T}(q::DataStructures.Deque{T}) at /home/ubuntu/.julia/v0.5/DataStructures/src/deque.jl:170
collect(itr) at array.jl:236

julia> [meth.module for meth in methods(collect)]
5-element Array{Module,1}:
 Base
 Base
 Base
 DataStructures
 Base

julia> first(methods(collect, (Deque,))).module
 DataStructures

In Julia 1.x the commands are:

  1. Base.nameof
  2. Base.parentmodule

Since this two methods are exported, also nameof and parentmodule works.

Tags:

Julia