Julia:`import` 和 `using` 的用例

Cir*_*exe 11 julia

So I read the documentation for using and import in Julia. However what this does not tell me is how I should be using these two statements in practice (and, given the lack of orthogonality, this is not too easy).

Case in point: let's put the following trivial code in "myfile.jl":

module MyModule
f() = 1
export f
end
import .MyModule # or: using .MyModule
Run Code Online (Sandbox Code Playgroud)
  • if I use import on the last line, then f is not exported to Main namespace. However, when I change "myfile.jl" (e.g. modifying the return value of f) and then re-include it, the function is replaced (this is the behaviour I wish for). (Note that I could explicitly import .MyModule: f, but this introduces unneeded redundancy; also, the real-life case will involve a long list of functions with long names. OK, I might also write a macro that uses names(Main.MyModule), but I somehow feel that this ought to be simpler.)

  • if I replace import by using, then this is reversed: f is now exported, but changing anything in the module now requires re-starting the Julia interpreter.

  • using both import and using exports only the first version of f() to the main namespace: when I update the code, only the first return value is used.

So my question is not about the behaviour of both statements import and using, which are documented (if not explained) in the linked page, but about the intent behind these. Why two statements when one would be enough? Why does one of these ignore all export directives? In which case am I supposed, in practice, to use each statement?

(version is 1.1.0. Also, this runs on a system without easy Pkg access, so I did not try Revise yet.)

Prz*_*fel 10

Julia 中的约定是使用,using PackageName除非您有特定的理由不这样做。

这种语言设计决策的动机仅仅是用户的舒适度。Julia 使用多分派,并且通常打包导出函数,这些函数对类型化参数进行操作(但是这些通常是abstract类型,因此函数功能不受限制)。

通过这种设计,实现它们的所有函数和方法都可以在同一个命名空间中,因为它们在特定于其包的参数类型上有所不同。因此,using将包带入覆盖现有方法实现的命名空间的情况非常罕见(然后 Julia 报告警告)。此过程还由包作者通过使用export关键字进行控制。

我认为这对你来说很奇怪,因为你已经习惯了像 Python 这样的语言。例如,numpy具有与默认函数完全相同的函数名称,并且没有以不同方式命名它们的好方法(例如,尝试考虑什么是名为sin:-)的函数的好替代方案)。因此,在 Python 中,您总是需要将函数导入到它们自己的命名空间中,可能使用别名,例如import numpy as np. 在使用这两种语言几年后,我会说 Julia 的方式很自然,而 Pytonish 的方式很奇怪:-)

关于import将单个函数从包中引入命名空间的可能性和可能性,我将其视为发生名称冲突情况的解决方法。如果您想将新方法实现添加到其他一些包(例如为+运算符定义新含义),您还需要明确地这样做。除此之外,您只需打字using,永不回头。