首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Pluto中使用局部Julia模

在Pluto中使用局部Julia模
EN

Stack Overflow用户
提问于 2022-03-11 14:48:05
回答 1查看 506关注 0票数 0

使用Julia1.7.2在Plutov0.18.0笔记本中导入本地模块的正确方法是什么?using关键字将导出的成员添加到朱莉娅的主命名空间中。给出一个样本模块,在foo.jl中,

代码语言:javascript
复制
module Foo
    export bar
    function bar()
        return "baz"
    end
end

以下代码单元格在冥王星笔记本中工作:

代码语言:javascript
复制
# "baz"
begin
    include("./foo.jl")
    using .Foo
    bar()
end

但是,如果我试图从另一个单元格调用bar,则会得到以下错误:

代码语言:javascript
复制
# UndefVarError: bar not defined
bar()

虽然我注意到Foo.bar()确实能工作。

如何在笔记本的命名空间中以直接访问其导出成员的方式添加自己的模块?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-28 10:09:02

这个讨论给出了一个可能的解决方案。它描述了一种获得模块引用的更好的方法,而不是我问题中的内容。

如果模块不是文件中的最后定义,则必须重新定义import函数。建议的名称是有一个名为"ingredients“的变体

代码语言:javascript
复制
#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)

代码语言:javascript
复制
#Main.Foo.jl.Foo
Foo = ingredients("My Library/Foo.jl").Foo

然后,使用模块引用,您必须手动将所有导出的变量导入全局范围:

代码语言:javascript
复制
#bar = bar (generic function with 1 method)
bar = Foo.bar
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71440280

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档