`eval(Symbol("varname")` causes `UndefVarError` although the variable is defined

I am revising the codes of COBRA.jl for using it on julia > 1.0.
https://github.com/opencobra/COBRA.jl/blob/master/test/p_all.jl
https://github.com/opencobra/COBRA.jl/blob/master/src/distributedFBA.jl (from Line 857)

During the test of the edited codes, I have got a strange error.
Here’s a simplified one causing the error.

function saveDistributedFBA(fileName::String, vars::Array{String,1} = ["minFlux", "rxnsList"], printLevel::Int=1)
  for i = 1:length(vars)
    if isdefined(Main, Symbol(vars[i])) # It is true when i=1
      println("The variable \"minFlux\" actually exists: the type is $(typeof((Main.minFlux)))")
      eval(Main.:minFlux) # This results in UndefVarError
    end
  end
end

I performed test by executing
(v1.1) pkg>test COBRA

Is it related to the scope of the variable or a misuse of eval?

Most likely that eval is always in global scope.

1 Like

Although that’s always been the case, so I’m not sure why that would break code from an earlier Julia version.

I can’t repro:

julia> function saveDistributedFBA(fileName::String, vars::Array{String,1} = ["minFlux", "rxnsList"], printLevel::Int=1)
         for i = 1:length(vars)
           if isdefined(Main, Symbol(vars[i])) # It is true when i=1
             println("The variable \"minFlux\" actually exists: the type is $(typeof((Main.minFlux)))")
             eval(Main.:minFlux) # This results in UndefVarError
           end
         end
       end
saveDistributedFBA (generic function with 3 methods)

julia> minFlux = 2
2

julia> saveDistributedFBA("foo")
The variable "minFlux" actually exists: the type is Int64

Yeah, this error is not reproducible when we do just in the REPL as shown in your reply. Actually, this function is in the Module COBRA, resulting conflicts of the scope as Stefan said.

Here is the revised codes for Julia > 1.0.
https://github.com/leejm516/COBRA.jl/tree/master-julia1.0

1 Like

Now try that in a script.

Is there any way to do a local scope eval?

There is not.

1 Like

Woah, thanks for the prompt reply!

Anyways, those interested in similar functionality might find this Stackoverflow answer helpful.