Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a list of modules imported by a given module

Tags:

julia

In the following example:

julia> module M
       using DataStructures
       end
Main.M

julia> names(Main.M, all=true, imported=true)
5-element Array{Symbol,1}:
 Symbol("#eval")
 Symbol("#include")
 :M
 :eval
 :include

we see that names does not list the names of the modules (in this case DataStructures) imported by a module (in our case Main.M) if they are not exported. My question is how to get a list of modules imported by a given module.

An additional question would be how to check what is the source of such a module (note that using e.g. Pkg.dependencies is not enough for it as the module might have been loaded first and then an active environment of the Julia session might have changed). If the second question does not have a good answer in general then it is enough for me to do this check against a UUID and a version of a package that comes from a global registry of Julia packages.

Thank you!

like image 567
Bogumił Kamiński Avatar asked Oct 15 '22 00:10

Bogumił Kamiński


1 Answers

You can get the modules loaded into another module by calling the C function jl_modules_using, I often define the following helper Julia binding:

modules(m::Module) = ccall(:jl_module_usings, Any, (Any,), m)

Note that this only works for things that have been brought in via using, not via import, e.g.:

julia> modules(m::Module) = ccall(:jl_module_usings, Any, (Any,), m)
modules (generic function with 1 method)

julia> module Foo
       import Pkg
       end

       modules(Foo)
2-element Array{Any,1}:
 Base
 Core

julia> module Bar
       using Pkg
       end

       modules(Bar)
3-element Array{Any,1}:
 Pkg
 Base
 Core

If you want a more accurate test of whether a module has been loaded (but without the information of who imported it) you can use Base.loaded_modules:

julia> Base.loaded_modules
Dict{Base.PkgId,Module} with 33 entries:
  SuiteSparse [4607b0f0-06f3-5cda-b6b1-a6196a1729e9]    => SuiteSparse
  SharedArrays [1a1011a3-84de-559e-8e89-a11a2f7dc383]   => SharedArrays
  REPL [3fa0cd96-eef1-5676-8a61-b3b8758bbffb]           => REPL
  Mmap [a63ad114-7e13-5084-954f-fe012c677804]           => Mmap
  ⋮                                                     => ⋮

I am sadly not sure why we don't have a nice list of modules that have bindings that have been imported into another module. I suggest opening an issue on the Julia tracker asking for that if you need it, there may be an easy way to get at it that I don't myself know.

like image 93
staticfloat Avatar answered Oct 21 '22 09:10

staticfloat