3

I am starting to write some Julia functions that rely on other packages for their computations. For example, in R, I will write the following if my function depends on the dplyr package.

foo <- function(x){
  require(dplyr) # the body part will use the package `dplyr`
  #body
}

What's the equivalent in Julia and, are they any best practices/suggestions when it comes to that? By now I am using using Pkg inside the body of the functions, but I am not sure about it. Thank you.

  • 2
    Since you ask about best practices, I'd mention that currently in R, the widely accepted best practice is [always use `library()`, never use `require()`](https://stackoverflow.com/a/51263513/903061). – Gregor Thomas Feb 02 '22 at 17:22

1 Answers1

2

You are probably looking for using. You can either using an entire package

using LinearAlgebra

or you can specify a list of just the specific things you want to use

using StasBase: fit, Histogram

There is also import but that is mostly used either (A) when you want to include a file, rather than a package or

(B) when you want to extend a function from another package (including Base, if you want!) for, e.g., your custom types.

struct Point{T}
    x::T
    y::T
end

import Base.+
function +(a::Point, b::Point)
    return Point(a.x + b.x, a.y + b.y)
end
julia> Point(3,5) + Point(5,7)
Point{Int64}(8, 12)

But unless you want to do that, you probably just need using.

The major difference is that you would not normally put your using statement within a function (rather put it at top level instead). Depending on code from another package only within a single function would arguably be a bit un-Julian.

cbk
  • 4,225
  • 6
  • 27
  • 1
    I think this isn't 100% the same, see the discussion on `require` here: https://stackoverflow.com/questions/5595512/what-is-the-difference-between-require-and-library - but depends on what functionality OP actually wants – Nils Gudat Feb 02 '22 at 16:53
  • Yeah, the use inside a function is definitely different. It may be a paradigm that doesn't really have an exact parallel in Julia – cbk Feb 02 '22 at 17:08
  • 2
    You can optionally precompile the package that you've just added. Some packages open much quicker if they have been precompiled. The 'plots' package is much improved by precompiling. – Francis King Feb 02 '22 at 18:22