I am new to Julia Lang. I am coming from the background of Matlab.
In Matlab, when pressing whos command I will get all variables in the current scope; and also, I can store them in another variable like x=whos; Is there such commands exists in Julia?
Example code in Matlab:
>> a=3;
>> b=4;
>> whos
Variables in the current scope:
Attr Name Size Bytes Class
==== ==== ==== ===== =====
a 1x1 8 double
b 1x1 8 double
prefix 1x16 16 char
Total is 18 elements using 32 bytes.
An Update:
whos()
... is not working either in iJulia or at the command prompt in Julia-1.0.0.
It is working in Julia-0.6.4, though.
On the other hand,
varinfo()
....prints information about the exported global variables in a module. For Example,
julia-1.0> varinfo()
name size summary
–––––––––––––––– ––––––––––– –––––––––––––––––––––––––––––––
Base Module
Core Module
InteractiveUtils 154.271 KiB Module
Main Module
PyPlot 781.872 KiB Module
ans 50.323 KiB Plots.Plot{Plots.PyPlotBackend}
myrepl 0 bytes typeof(myrepl)
x 88 bytes 1×6 Array{Int64,2}
y 0 bytes typeof(y)
Hope, this is found useful.
You can use Julia's whos functions just like that Matlab command.
julia> whos()
Base Module
Core Module
Main Module
ans Nothing
julia> x = 5
5
julia> whos()
Base Module
Core Module
Main Module
ans Int64
x Int64
Any modules (packages/libraries) you import into your local scope (using using) will also show up in the list (as Modules, like Base, Core, and Main above).
Additionally, you can ask about names exported by Modules. Base is the module containing the standard library.
julia> whos(Base)
! Function
!= Function
!== Function
$ Function
% Function
& Function
* Function
+ Function
.... (lots and lots more)
Considering that that result scrolls way off my screen, you can understand why you'd want to filter the results. For that you can use Regexes. (For more info on Julia's regexes, see this manual section)
julia> whos(r"M")
Main Module
julia> whos(Base, r"Match"i)
DimensionMismatch DataType
RegexMatch DataType
each_match Function
eachmatch Function
ismatch Function
match Function
matchall Function
I wasn't aware of the whos function before you asked, so thanks for helping me learn something new too. :)
Julia issue #3393 on github is about adding memory sizes to the whos output. It also references making whos return a value rather than just printing the information out.
Not sure if there is something better, but
names(Main)[4:end]
seems to work. The [4:end] part is because it includes :Main, :Core and :Base which I think you would not want. I hope they will always be at the beginning.
whos() is not available in newer versions of Julia (1.0 onward). Use varinfo() instead. For example, varinfo(Core,r".*field.*")
As of version 1.1 there is also the #locals macro
The experimental macro Base.#locals returns a dictionary of current local variable names and values
Release notes
Related
I know this question has been asked and answered before, but none of the many answers work for me as described.
What is the procedure for reloading a module that I'm working on in Julia (1.6)?
For example, I have
module MyModule
export letters
const letters = String('A':'Z')
end
and I want the be able to load the module, make changes to letters in the module's file, and then reload the module and have those changes reflected in subsequent uses of letters. This seems simple enough, but I can't get it to work.
I've tried
include("src/MyModule.jl")
using .MyModule
but if I change the definition of letters in MyModule.jl and then
include("src/MyModule.jl")
letters doesn't change, unless I fully qualify its use each time with Main.MyModule.letters: using Main.MyModule; letters refers, for example, to the old definition.
How do I reload a module under development so that I can refer to its definitions without fully qualifying them (and without having an unqualified shadow definition always lying around)?
I would just use Revise.jl and wrap everything in functions:
module MyModule
export letters
letters(char_start, char_end) = char_start:char_end |> String
end
julia> using Revise
julia> includet("src/MyModule.jl")
julia> using .MyModule
julia> letters('l', 'p')
"lmnop"
module MyModule
export letters
letters(char_start, char_end) = char_start:char_start |> String
end
julia> letters('l', 'p')
"l"
const is for defining things that you do not want to modify, so I would not expect your original version to work as expected. Revise.jl should also throw a redefinition error if you try to change it
In general though, it's usually much nicer (and easier too!) to just put everything in a package and use the usual using/import syntax. PkgTemplates.jl is great for this
If you would like to redefine consts though, I would definitely recommend checking out Pluto.jl
I saw this example in the Julia language documentation. It uses something called Base. What is this Base?
immutable Squares
count::Int
end
Base.start(::Squares) = 1
Base.next(S::Squares, state) = (state*state, state+1)
Base.done(S::Squares, s) = s > S.count;
Base.eltype(::Type{Squares}) = Int # Note that this is defined for the type
Base.length(S::Squares) = S.count;
Base is a module which defines many of the functions, types and macros used in the Julia language. You can view the files for everything it contains here or call whos(Base) to print a list.
In fact, these functions and types (which include things like sum and Int) are so fundamental to the language that they are included in Julia's top-level scope by default.
This means that we can just use sum instead of Base.sum every time we want to use that particular function. Both names refer to the same thing:
Julia> sum === Base.sum
true
Julia> #which sum # show where the name is defined
Base
So why, you might ask, is it necessary is write things like Base.start instead of simply start?
The point is that start is just a name. We are free to rebind names in the top-level scope to anything we like. For instance start = 0 will rebind the name 'start' to the integer 0 (so that it no longer refers to Base.start).
Concentrating now on the specific example in docs, if we simply wrote start(::Squares) = 1, then we find that we have created a new function with 1 method:
Julia> start
start (generic function with 1 method)
But Julia's iterator interface (invoked using the for loop) requires us to add the new method to Base.start! We haven't done this and so we get an error if we try to iterate:
julia> for i in Squares(7)
println(i)
end
ERROR: MethodError: no method matching start(::Squares)
By updating the Base.start function instead by writing Base.start(::Squares) = 1, the iterator interface can use the method for the Squares type and iteration will work as we expect (as long as Base.done and Base.next are also extended for this type).
I'll grant that for something so fundamental, the explanation is buried a bit far down in the documentation, but http://docs.julialang.org/en/release-0.4/manual/modules/#standard-modules describes this:
There are three important standard modules: Main, Core, and Base.
Base is the standard library (the contents of base/). All modules
implicitly contain using Base, since this is needed in the vast
majority of cases.
Given a function object f, how do I find:
Function's name.
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.
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
#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.
In Julia 1.x the commands are:
Base.nameof
Base.parentmodule
Since this two methods are exported, also nameof and parentmodule works.
Not exactly the answer but closely related: you can find the file name and line number of f using functionloc(f)
This is probably a newbie question... but is it possible to show the definition of a (user defined) function? While debugging/optimizing it is convenient to quickly see how a certain function was programmed.
Thanks in advance.
You can use the #edit macro, which is supposed to take you to the definition of a method, similarly to how the #which macro which shows the file and line # where that particular method was defined, for example:
julia> #which push!(CDFBuf(),"foo")
push!{T<:CDF.CDFBuf}(buff::T, x) at /d/base/DA/DA.jl:105
julia> #which search("foobar","foo")
search(s::AbstractString, t::AbstractString) at strings/search.jl:146
Note that methods that are part of Julia will show a path relative to the julia source directory "base".
While this is not an automatic feature available with Julia in general (as pointed out by Stefan), if you add docstrings when you define your initial function, you can always use the help?> prompt to query this docstring. For example
julia> """mytestfunction(a::Int, b)""" function mytestfunction(a::Int, b)
return true
This attaches the docstring "mytestfunction(a::Int, b)" to the function mytestfunction(a::Int, b). Once this is defined, you can then use the Julia help prompt (by typing ? at the REPL), to query this documentation.
help?> mytestfunction
mytestfunction(a::Int, b)
Is there any syntax that does something similar to MATLAB's "clear" i.e. if I have a global variable "a". How do I get rid of it? How do I do the analog of
clear a
See the latest answer to this question here: https://docs.julialang.org/en/v1/manual/faq/#How-do-I-delete-an-object-in-memory%3F
Retrieved from the docs:
Julia does not have an analog of MATLAB’s clear function; once a name
is defined in a Julia session (technically, in module Main), it is
always present.
If memory usage is your concern, you can always replace objects with
ones that consume less memory. For example, if A is a gigabyte-sized
array that you no longer need, you can free the memory with A = 0. The
memory will be released the next time the garbage collector runs; you
can force this to happen with gc().
Julia 0.6 < 1.0
In Julia 0.6. You can remove the variable and free up it's memory by calling clear!().
You have to call clear! on the symbolic name of the variable:
julia> x = 5
5
julia> sizeof(x)
8
julia> clear!(:x)
julia> sizeof(x)
0
As DFN pointed out, this won't actually remove the objects but set them to nothing. This is useful for freeing up memory from you workspace as you can "delete" the memory footprint for non-constant objects.
Julia 1.0+
This does not work in Julia 1.0+. If you are using 1.0+ you will have to set the object to Nothing and let the garbage collector take it from there.
This is from the official docs here.
As of 0.3.9, it's possible to clear all global variables (get a new workspace), through the workspace() function.
It's also possible to get the variables from the last workspace by using LastMain (e.g. LastMain.foobar).
So currently the only way of doing what you desire, is to clear everything and transfer everything but the variable you want to your new workspace.
Currently, one doesn't. There is, however, an issue to track that feature:
https://github.com/JuliaLang/julia/issues/2385
For Julia-0.6.4,
clear!(:x)
is working as mentioned by #niczky AND it's working in iJulia.
However, for Julia-1.0.0,
clear!(:x)
... throws up the following:
ERROR: UndefVarError: clear! not defined
Stacktrace:
[1] top-level scope at none:0
So, it's broken for Julia-1.0.0.
Absolutely clear!(:x) does not work with julia 0.6.0 in notebook(IJulia)! You may choose to use x = 0 as an alternative.