LoginSignup
33
18

More than 5 years have passed since last update.

Juliaのusingとimportについて〜いつ省略できるのか

Last updated at Posted at 2018-09-26

Julia 1.0における、usingとimportの違いについてまとめてみた。
https://docs.julialang.org/en/v1.0/manual/modules/
を参考にした。

テストモジュール

まず、テストモジュールとして、

test.jl
module Mymodule1 #エクスポートするfunctionはなし
    function test()
        println("Mymodule1: test")
    end
    function test2()
        println("Mymodule1: test2")
    end
end

module Mymodule2
    export test #test()だけをexportしておく
    function test()
        println("Mymodule2: test")
    end
    function test2()
        println("Mymodule2: test2")
    end
end

の二つを用意する。

using

まず、usingを試してみる。

test.jl
using .Mymodule1

をやってみる。.Mymodule1の先頭のドット.は自前のモジュールの場所を表す。

test.jl
using .Mymodule1
test()

はtestがないと怒られる。

test.jl
using .Mymodule1
Mymodule1.test()

は表示される。したがって、usingを使うときには、モジュール名.が必要そうだ。
一方、

test.jl
using .Mymodule2
test()

は動く。これは、Mymodule2において、exportがつけられているからである。もちろん、

test.jl
using .Mymodule2
test2()

は怒られる。なぜなら、test2はexportされていないからである。
また、

test.jl
using .Mymodule2: test2
test2()

であれば、test2を呼ぶことができる。これは、:を使ったことにより、exportを書いたことと同等の効果が得られたと考えられる。

よって、省略して呼べるのは、
- exportに書いたfunction
- using モジュール名:function名 と書いたfunction

ということがわかる。

import

次はimportについて。

test.jl
import .Mymodule1
test()

は怒られる。

test.jl
import .Mymodule1
Mymodule1.test()

としなければならない。

他には、

test.jl
import .Mymodule1.test,.Mymodule1.test2
test()
test2()

があるが、この場合はMymodule1を省略して呼べる。

test.jl
import .Mymodule1:test,test2
test()
test2()

でも、Mymodule1を省略して呼べる。
では、Mymodule2についてはどうだろうか?

test.jl
import .Mymodule2
test()

は怒られる。exportに書いてあっても関係がないようだ。

test.jl
import .Mymodule2.test2
test2()

は呼べる。

よって、省略して呼べるのは、
- import モジュール名.function名
- import モジュール名:function名
の二つである。

usingとimportの違い

usingを使うと、exportに入っているものはすべてモジュール名なしで(省略して)呼ぶことができる。しかし、たくさんexportにfunctionがある場合、using モジュール名を使うと、使う予定のないものまで省略して呼べてしまうので、面倒なことになることもある。
一方、importの場合、exportの有無の関係なしに、デフォルトではモジュール名をつけなければならない。しかし、import モジュール名.function名あるいは import モジュール名:function名とすれば、そのfunctionだけモジュール名を省略して呼ぶことができる。汎用的なライブラリを呼ぶときは、importで必要なものだけ呼べば、不必要に名前を使われることはない。

33
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
18