【问题标题】:Syntax to automatically export functions in a Julia module在 Julia 模块中自动导出函数的语法
【发布时间】:2021-05-15 15:41:30
【问题描述】:

我觉得列出每个函数 来导出有点乏味。这样做(几年前的pulled from a thread)感觉很糟糕:

module DemoModule
  # 25 functions here...

  for n in names(current_module(), true)
    if Base.isidentifier(n) && n ∉ (Symbol(current_module()), :eval)
      @eval export $n
    end
  end
end

是否有语法糖来标记要自动导出的函数?我想对 Python 的公共/私有方法的语法做一个类比:

module DemoModule

  function add(a, b)
    # `add` is exported automatically
    return _private_helper(a) + _private_helper(b)
  end

  function _private_helper(a)
    # `_private_helper` should not be exported, so it's marked with a `_`
    return a
  end
end

一些额外的背景


编辑:提出可能的妥协:ExportPublic.jl

【问题讨论】:

    标签: design-patterns module julia


    【解决方案1】:

    这在 Julia 社区的讨论中通常被认为是不推荐的。

    但是有一个包ExportAll.jl 就是这样。

    module Bar
        using ExportAll
        function foo()
            1
        end
    
        function bar()
            2
        end
        @exportAll()
    end
    

    现在你可以这样做了:

    julia> using Main.Bar
    
    julia> bar()
    2
    

    【讨论】:

    • 谢谢,我不知道 ExportAll 包。不过你是对的:这正是我不想想要做的。我想我可以调整宏以根据方法名称模拟公共/私有。
    • 我对它进行了一段时间的修改并最终创建了ExportPublic.jl:github.com/hayesall/ExportPublic.jl 我会再玩一些,它可能会/可能不会最终适合我喜欢的工作流程。
    • SubString(string(e), 8, 8) 做什么?规则是什么?
    • s 转换为String a 在其第8 个字符上创建一个view
    猜你喜欢
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    • 2017-12-23
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 2021-04-29
    相关资源
    最近更新 更多