Alex Craft
Alex Craft

Reputation: 15386

How to use package in Julia without importing it?

If you write it imports all bunch of methods into the current scope.

using Plots
plot(rand(5,5))

I need only one method, is it possible to write the same code but without using or importing anything, I don't want to pollute the current scope with Plots exports and don't mind to prefix it with package name every time I use it.

Plots.plot(rand(5,5))

Upvotes: 7

Views: 383

Answers (3)

David Sainez
David Sainez

Reputation: 6976

import will bring a module into scope without any of its exported names. You can still use qualified names to reference names within the imported module:

import Plots
Plots.plot(rand(5,5))

To avoid using the qualified name, you can create a binding to a new name:

const plot_from_plots = Plots.plot

Upvotes: 7

fredrikekre
fredrikekre

Reputation: 10984

In addition to the other suggestions; I wrote a package (ImportMacros) which lets you import functions with other names without bringing anything else into scope:

julia> using ImportMacros

julia> @import Plots.plot as plt

julia> plt
plot (generic function with 3 methods)

so Plots.plot is available as plt, yet Plots is undefined:

julia> Plots
ERROR: UndefVarError: Plots not defined

Upvotes: 2

GBlodgett
GBlodgett

Reputation: 12819

According to the Julia website you should be able to do:

using Plots: plot

Which will only bring plot() in scope


See Module aliasing in Julia for how to create an alias for the method

Upvotes: 6

Related Questions