I'm creating a module A that can extend functions defined in module B (which means module A may have using B or import B). However I don't want to load module B unless the user already has add B to their system. An example code would be like so:
module A
struct MyStruct{T}; end
if(#= module B exists =#)
import B: myFn
function myfn(x::MyStruct)
# ...
end
end
An analogy of this would be the use of #ifndef ... #define ... #endif in C++ header files. Is there a way for me to check that user has added B, and is this a good pattern to use when building modules?
In order to check if a package is installed on the user's system is to peek through the Base method Pkg.Installed (read more about it here):
"moduleB" ∈ keys(Pkg.installed())
returns True if the requested "moduleB" is installed.
If you need to find out that a package is loaded then use isdefined()
(Main, :moduleB)
Hope that helps!
Related
Although this question has been asked before, it appears that much has changed with respect to modules in Julia V1.0.
I'm trying to write a custom module and do some testing on it. From the Julia documentation on Pkg, using the dev command, there is a way to create a git tree and start working.
However, this seems like overkill at this point. I would like to just do a small local file, say mymodule.jl that would be like:
module MyModule
export f, mystruct
function f()
end
struct mystruct
x::Integer
end
end # MyModule
It appears that it used to be possible to load it with
include("module.jl")
using MyModule
entering the include("module.jl"), it appears that the code loads, i.e. there is no error, however, using MyModule gives the error:
ArgumentError: Package MyModule not found in current path:
- Run `import Pkg; Pkg.add("MyModule")` to install the MyModule package.
I notice that upon using include("module.jl"), there is access to the exported function and struct using the full path, MyModule.f() but I would like the shorter version, just f().
My question then is: to develop a module, do I need to use the Pkg dev command or is there a lighter weight way to do this?
In order to use a local module, you must prefix the module name with a ..
using .MyModule
When using MyModule is run (without the .), Julia attempts to find a module called MyModule installed to the current Pkg environment, hence the error.
Is there a way to pull ALL the docstrings from the following module main, including the docstrings of module nested, which reside inside module main, without already knowing what modules are inside module main?
"This is Module main"
module main
"This is fA()"
fA(x) = x
"This is module nested"
module nested
"This is fB()"
fB(x) = x
end
end
I can get the docstrings for module main and module nested, assuming I already know that module nested exists inside module main.
? main
This is Module main
? main.nested
This is Module nested
I am familiar with names(), which helps, but not that much in its simplest incantation:
names(main, all = true)
7-element Array{Symbol,1}:
Symbol("##meta#252")
Symbol("#eval")
Symbol("#fA")
:eval
:fA
:main
:nested
Interpreting the output of names()is not easy: it's not obvious that nested is a module inside main.
The question is not entirely clear, but here is some useful code:
# check if a symbol is a nested module
issubmodule(m::Module, s::Symbol) = isa(eval(m,s),Module) && module_name(m) != s
# get a list of all submodules of module m
submodules(m) = filter(x->issubmodule(m,x),names(m,true))
# get a list of all docstring bindings in a module
allbindings(m) = [ [y[2].data[:binding] for y in x[2].docs]
for x in eval(m,Base.Docs.META)]
# recursively get all docstrings from a module and submodules
function alldocs(m)
thedocs = map(x->Base.Docs.doc(x[1]),allbindings(m))
return vcat(thedocs,map(x->alldocs(eval(m,x)),submodules(m))...)
end
Now you have:
julia> alldocs(main)
This is fA()
This is Module main
This is module nested
This is fB()
Hope this helps.
2018 Update: Be sure to check all the responses, as the answer to this question has changed multiple times over the years. At the time of this update, the Revise.jl answer is probably the best solution.
I have a file "/SomeAbsolutePath/ctbTestModule.jl", the contents of which are:
module ctbTestModule
export f1
f1(x) = x + 1
end
I fire up Julia in a terminal, which runs "~/.juliarc.jl". The startup code includes the line:
push!(LOAD_PATH, "/SomeAbsolutePath/")
Hence I can immediately type into the Julia console:
using ctbTestModule
to load my module. As expected f1(1) returns 2. Now I suddenly decide I want to edit f1. I open up "/SomeAbsolutePath/ctbTestModule.jl" in an editor, and change the contents to:
module ctbTestModule
export f1
f1(x) = x + 2
end
I now try to reload the module in my active Julia session. I try
using ctbTestModule
but f1(1) still returns 2. Next I try:
reload("ctbTestModule")
as suggested here, but f1(1) still returns 2. Finally, I try:
include("/SomeAbsolutePath/ctbTestModule.jl")
as suggested here, which is not ideal since I have to type out the full absolute path since the current directory might not be "/SomeAbsolutePath". I get the warning message Warning: replacing module ctbTestModule which sounds promising, but f1(1) still returns 2.
If I close the current Julia session, start a new one, and type in using ctbTestModule, I now get the desired behaviour, i.e. f1(1) returns 3. But obviously I want to do this without re-starting Julia.
So, what am I doing wrong?
Other details: Julia v0.2 on Ubuntu 14.04.
The basis of this problem is the confluence of reloading a module, but not being able to redefine a thing in the module Main (see the documentation here) -- that is at least until the new function workspace() was made available on July 13 2014. Recent versions of the 0.3 pre-release should have it.
Before workspace()
Consider the following simplistic module
module TstMod
export f
function f()
return 1
end
end
Then use it....
julia> using TstMod
julia> f()
1
If the function f() is changed to return 2 and the module is reloaded, f is in fact updated. But not redefined in module Main.
julia> reload("TstMod")
Warning: replacing module TstMod
julia> TstMod.f()
2
julia> f()
1
The following warnings make the problem clear
julia> using TstMod
Warning: using TstMod.f in module Main conflicts with an existing identifier.
julia> using TstMod.f
Warning: ignoring conflicting import of TstMod.f into Main
Using workspace()
However, the new function workspace() clears Main preparing it for reloading TstMod
julia> workspace()
julia> reload("TstMod")
julia> using TstMod
julia> f()
2
Also, the previous Main is stored as LastMain
julia> whos()
Base Module
Core Module
LastMain Module
Main Module
TstMod Module
ans Nothing
julia> LastMain.f()
1
Use the package Revise, e.g.
Pkg.add("Revise") # do this only once
include("src/my_module.jl")
using Revise
import my_module
You may need to start this in a new REPL session. Notice the use of import instead of using, because using does not redefine the function in the Main module (as explained by #Maciek Leks and #waTeim).
Other solutions: Two advantages of Revise.jl compared to workspace() are that (1) it is much faster, and (2) it is future-proof, as workspace() was deprecated in 0.7, as discussed in this GitHub issue:
julia> VERSION
v"0.7.0-DEV.3089"
julia> workspace()
ERROR: UndefVarError: workspace not defined
and a GitHub contributor recommended Revise.jl:
Should we add some mesage like "workspace is deprecated, check out Revise.jl instead"?
Even in Julia 0.6.3, the three previous solutions of workspace(), import, and reload fail when a module called other modules, such as DataFrames. With all three methods, I got the same error when I called that module the second time in the same REPL:
ERROR: LoadError: MethodError: all(::DataFrames.##58#59, ::Array{Any,1}) is ambiguous. Candidates: ...
I also got many warning messages such as:
WARNING: Method definition macroexpand(Module, ANY) in module Compat at /Users/mmorin/.julia/v0.6/Compat/src/Compat.jl:87 overwritten in module Compat at /Users/mmorin/.julia/v0.6/Compat/src/Compat.jl:87.
Restarting the Julia session worked, but it was cumbersome. I found this issue in the Reexport package, with a similar error message:
MethodError: all(::Reexport.##2#6, ::Array{Any,1}) is ambiguous.
and followed the suggestion of one contributor:
Does this happen without using workspace()? That function is notorious for interacting poorly with packages, which is partly why it was deprecated in 0.7.
In my humble opinion, the better way is to use import from the very beginning instead of using for the reported issue.
Consider the module:
module ModuleX1
export produce_text
produce_text() = begin
println("v1.0")
end
println("v1.0 loaded")
end
Then in REPL:
julia> import ModuleX1
v1.0 loaded
julia> ModuleX1.produce_text()
v1.0
Update the code of the module and save it:
module ModuleX1
export produce_text
produce_text() = begin
println("v2.0")
end
println("v2.0 loaded")
end
Next, in the REPL:
julia> reload("ModuleX1")
Warning: replacing module ModuleX1
v2.0 loaded
julia> ModuleX1.produce_text()
v2.0
Advantages of using import over using:
avoiding ambiguity in function calls (What to call: ModuleX1.produce_text() or produce_text() after reloading?)
do not have to call workspace() in order to get rid of ambiguity
Disadvantages of using import over using:
a fully qualified name in every call for every exported name is needed
Edited: Discarded "full access to the module, even to the not-exported names" from "Disadvantages..." according to the conversation below.
workspace() has been deprecated.
You can reload("MyModule") in an active REPL session, and it works as expected: changes made to the source file that contains MyModule are reflected in the active REPL session.
This applies to modules that have been brought into scope by either import MyModule or using MyModule
I wanted to create a new module from scratch, and tried the different answers with 1.0 and didn’t get a satisfactory result, but I found the following worked for me:
From the Julia REPL in the directory I want to use for my project I run
pkg> generate MyModule
This creates a subdirectory like the following structure:
MyModule
├── Project.toml
└── src
└── MyModule.jl
I put my module code in MyModule.jl. I change to the directory MyModule (or open it in my IDE) and add a file Scratch.jl with the following code:
using Pkg
Pkg.activate(".")
using Revise
import MyModule # or using MyModule
Then I can add my code to test below and everything updates without reloading the REPL.
I battled to get Revise.jl to work for me, probably because I also use code generation with OOPMacro #class . I had to also call revise(...) See https://timholy.github.io/Revise.jl/stable/limitations/#Limitations-1.
I have been struggling with this problem for up to 5 years and finally got something that works for me that don't involve manually running my main module in the IDE repl after EVERY SMALL CHANGE :'(
Here is some of my code I use to force a revise and exit early when running tests when there were revise errors:
# Common code I include into my test files now:
using Pkg
using Revise
# force include module
Pkg.activate("MyModule")
include("../src/MyModule.jl")
Pkg.activate("MyModule/test")
using Revise
# if there were any revise errors which means some compilation error or
# some change that requires a manual rerun or restart.
# then force you to fix it, rather that running lying tests..
for (k, e) in Revise.queue_errors
if !isnothing(e)
warn(logger, "Something went wrong while revising, you probably have a compile error in this file:")
throw(e)
end
end
module TestSomethingModule
using Revise
using MyModule
revise(MyModule)
...
# then you can call MyModule.doSomithing in a test and it actually updates
end
For some reason, in my Prolog module I want to be able to consult a file, but like if it was consulted from another module (e.g. user).
Say I have a file named myfile.pl containing:
foo(1).
Normally, if in module mymodule I execute consult(myfile), what I have is a new predicate mymodule:foo/1.
I would like to be able to consult the file from module mymodule but the resulting predicate be like user:foo/1.
Is this possible?
Did you tried to call consult(user:myfile) from within your mymodule module?
I have modeled my project in alloy, and I want to separate the run part from the modeled part of my project.
In some fact and predicate I use the add function in cardinality comparison.
Here is an example :
#relation1 = add[ #(relation2), 1]
When the run part and the model part are in the same file all work successfully.
But when I separate them in 2 files, I have the following syntax error :
The name "add" cannot be found.
I thought it needed to open the integer module where there is an add function, so I have opened it it the header of the model part.
But then the runtime ask me to specify the scope of this/Univ.
You must specify a scope for sig "this/Univ"
Here is an example :
first the model in one module
module solo
open util/ordering [A] as chain
//open util/integer
sig A{ b : set B}
fact { all a : A - chain/last | #(a.next.b) = add[ #(a.b), 2]}
sig B{}
then the run part in another module :
module due
open solo
run {#(solo/chain/first.b) = 2 }for 10 B, 5 A
when I call it like this I have the "the name add cannot be found" error.
When I uncomment the integer module opening, I have the "You must specify a scope for sig "this/Univ"" error.
What should I do that to make it works?
If I'm not mistaken + is the union operator and thus can't be used to perform additions.
Which version of alloy are you using ?
I think the add[Int,Int] function was added recently, before it used to be plus[int,int].
You might want to try plus[Int,Int] and see if it solves your problem.
Else it would be nice to have access to your models. Maybe the error comes from elsewhere.