What is the best way to use a module inside a function

I am not able to use the function syntax below

function f()
        using DataFrames
        return Dataframe(x=[1,2],y=[3,4])
end

gives syntax: "using" expression not at top level error message, I searched the error message, but wasn’t able to implement the solution because it is related to writing module. To work around this limitation temporarily I wrote the function as

function f()   
    return Dict(x=>[1,2],y=>[3,4])    
end

However, the former function structure is more efficient to my work, how can I use it?

2 Likes

Module cannot be defined inside a function. The keyword using cannot be used inside of function. What I usually do is something like this:

module mmmmPoiss_energy
using FinEtools
using FinEtoolsHeatDiff
using Test
import LinearAlgebra: cholesky
function test()
  A = 1.0 # dimension of the domain (length of the side of the square)
  thermal_conductivity = [i==j ? one(FFlt) : zero(FFlt) for i=1:2, j=1:2]; # conductivity matrix
  Q = -6.0; # internal heat generation rate
  function getsource!(forceout::FFltVec, XYZ::FFltMat, tangents::FFltMat, fe_label::FInt)
    forceout[1] = Q; #heat source
  end
  N = 2;# number of subdivisions along the sides of the square domain
...
  true
end
end
using .mmmmPoiss_energy
mmmmPoiss_energy.test()

That is I define a module with functions and such in order to protect the global environment from anything that I wish to define, and conversely to protect the things I wish to define from inadvertently using variables in the global environment. So your use case might be handled as:

module m1
using DataFrames
function f()
        return DataFrame(x=[1,2],y=[3,4])
end
end
using .m1
m1.f()
7 Likes

Thanks for the reply. Now, I want to keep the module file separately, and import to the main code block. I did this by the following piece of code

include("m1_module_file")
using .m1

Is there a way to use module file just by writing using .m1 without adding line include(...) ?

Not yet: https://GitHub.com/JuliaLang/Julia/issues/4600

2 Likes