首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Julia @eval world age missmatch

Julia @eval world age missmatch
EN

Stack Overflow用户
提问于 2019-05-23 17:51:30
回答 1查看 130关注 0票数 1

我正在尝试使用julia @eval功能来仅按需加载PyPlot包。然而,我经常遇到世界时代的错位。下面是我尝试按需绘制的最小示例

代码语言:javascript
复制
function CreateMatrix(Ncount;Plot=true)
    TheMatrix = fill(0.0,Ncount,Ncount)

    if Plot
        @eval using PyPlot
        ###"Plot the Matrix"
        PyPlot.figure()
        PyPlot.imshow(abs.(TheMatrix))
        PyPlot.colorbar()
    end
    return TheMatrix
end

CreateMatrix(10;Plot=false)
CreateMatrix(10;Plot=true)

使用输出

代码语言:javascript
复制
ERROR: LoadError: MethodError: no method matching figure()
The applicable method may be too new: running in world age 25063, while current world is 25079.
Closest candidates are:
  figure(!Matched::Any...; kws...) at ~/.julia/packages/PyPlot/fZuOQ/src/PyPlot.jl:148 (method too new to be called from this world context.)
Stacktrace:
 [1] #CreateMatrix#3(::Bool, ::Function, ::Int64) at myfile.jl:7
 [2] (::getfield(Main, Symbol("#kw##CreateMatrix")))(::NamedTuple{(:Plot,),Tuple{Bool}}, ::typeof(CreateMatrix), ::Int64) at ./none:0
 [3] top-level scope at none:0
 [4] include at ./boot.jl:317 [inlined]
 [5] include_relative(::Module, ::String) at ./loading.jl:1044
 [6] include(::Module, ::String) at ./sysimg.jl:29
 [7] exec_options(::Base.JLOptions) at ./client.jl:231
 [8] _start() at ./client.jl:425
in expression starting at myfile.jl:16

有人知道如何正确使用@eval功能吗?

编辑

其中一个注释建议包装绘图命令并使用@noinline进行注释,如下所示,但这不起作用。

代码语言:javascript
复制
function CreateMatrix(Ncount;Plot=false)
    TheMatrix = fill(0.0,Ncount,Ncount)

    if Plot
        @eval using PyPlot
        ###"Plot the Matrix"
        ThePlotting(TheMatrix)
    end
    return TheMatrix
end

@noinline function ThePlotting(TheMatrix)
    PyPlot.figure()
    PyPlot.imshow(abs.(TheMatrix))
    PyPlot.colorbar()
end

CreateMatrix(10;Plot=false)
CreateMatrix(10;Plot=true)

我运行的是julia版本1.0.2

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-24 03:41:23

您可以像这样实现它:

代码语言:javascript
复制
function CreateMatrix(Ncount;Plot=true)
    TheMatrix = fill(0.0,Ncount,Ncount)

    if Plot
        if isdefined(Main, :PyPlot)
            println("PyPlot already loaded")
            PyPlot.figure()
            PyPlot.imshow(abs.(TheMatrix))
            PyPlot.colorbar()
        else
            println("PyPlot loading PyPlot")
            @eval using PyPlot
            Base.invokelatest(PyPlot.figure)
            Base.invokelatest(PyPlot.imshow, abs.(TheMatrix))
            Base.invokelatest(PyPlot.colorbar)
        end
    end
    return TheMatrix
end

我已经使用了conditional来允许您查看在重复调用函数时执行哪个分支。

最初,我认为在调用非内联函数时,Julia允许世界年龄变化(但事实证明它是严格的)。

最后,一般来说,不写这样的代码可能更安全,而是简单地在顶级作用域中加载模块(可能是有条件的)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56272550

复制
相关文章

相似问题

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