使用Julia1.7.2在Plutov0.18.0笔记本中导入本地模块的正确方法是什么?using关键字将导出的成员添加到朱莉娅的主命名空间中。给出一个样本模块,在foo.jl中,
module Foo
export bar
function bar()
return "baz"
end
end以下代码单元格在冥王星笔记本中工作:
# "baz"
begin
include("./foo.jl")
using .Foo
bar()
end但是,如果我试图从另一个单元格调用bar,则会得到以下错误:
# UndefVarError: bar not defined
bar()虽然我注意到Foo.bar()确实能工作。
如何在笔记本的命名空间中以直接访问其导出成员的方式添加自己的模块?
发布于 2022-03-28 10:09:02
这个讨论给出了一个可能的解决方案。它描述了一种获得模块引用的更好的方法,而不是我问题中的内容。
如果模块不是文件中的最后定义,则必须重新定义import函数。建议的名称是有一个名为"ingredients“的变体
#ingredients (generic function with 1 method)
function ingredients(path::String)
# this is from the Julia source code (evalfile in base/loading.jl)
# but with the modification that it returns the module instead of the last object
name = Symbol(basename(path))
m = Module(name)
Core.eval(m,
Expr(:toplevel,
:(eval(x) = $(Expr(:core, :eval))($name, x)),
:(include(x) = $(Expr(:top, :include))($name, x)),
:(include(mapexpr::Function, x) = $(Expr(:top, :include))(mapexpr, $name, x)),
:(include($path))))
m
end然后模块可以像这样加载(我不知道为什么要说ingredients().Foo)
#Main.Foo.jl.Foo
Foo = ingredients("My Library/Foo.jl").Foo然后,使用模块引用,您必须手动将所有导出的变量导入全局范围:
#bar = bar (generic function with 1 method)
bar = Foo.barhttps://stackoverflow.com/questions/71440280
复制相似问题