Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

julia

Given a function object f, how do I find:

  1. Function's name.
  2. Module(s) of its method(s)?

In Julia 0.4 I was able to find name using f.env.name, but no tips for module. For Julia 0.5 I wasn't able to find any of two.

like image 385
ffriend Avatar asked Aug 07 '16 22:08

ffriend


2 Answers

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
like image 142
Lyndon White Avatar answered Oct 07 '22 14:10

Lyndon White


@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.

like image 30
Fengyang Wang Avatar answered Oct 07 '22 13:10

Fengyang Wang