I've been struggling on this problem for quite a while, but I still don't understand why Mathematica is unable to recognize a function definition where the rhs is an Import
command.
Let me introduce the problem.
Consider the following Mathematica Package
(*Package v1*)
BeginPackage["test`"]
testFun::usage = "testFun[]";
Begin["`Private`"]
packageDirectory = $InputFileName // DirectoryName;
fModule[] := Module[{},
f[x_] = Import[FileNameJoin[{packageDirectory,"fun.m"}]];
];
testFun[xx_] := Module[{},
fModule[];
Table[f[i], {i, xx}]
];
End[] (* `Private` *)
EndPackage[]
where the file fun.m
acts as simple container for the definition of the body of f
, e.g.
x^2
When testFun[5]
is called in Mathematica Notebook the result is
{x^2, x^2, x^2, x^2, x^2}
which means that the pattern x_
is not recognized when fModule[]
is called.
The weird fact is that moving the defintion of f[x]
outside the module, i.e. like
(*Package v2*)
BeginPackage["test`"]
testFun::usage = "testFun[]";
Begin["`Private`"]
packageDirectory = $InputFileName // DirectoryName;
f[x_] = Import[FileNameJoin[{packageDirectory,"fun.m"}]];
fModule[] := Module[{},
f[x_] = Import[FileNameJoin[{packageDirectory,"fun.m"}]];
];
testFun[xx_] := Module[{},
(*fModule[];*)
Table[f[i], {i, xx}]
];
End[] (* `Private` *)
EndPackage[]
the definition of f[x]
is properly recognized!
Also, everything works if I run the code (Package v1) directly in the FrontEnd!
In my actual code I need the definition of f[x]
to happen inside the module using the Import
.
That's because the expression to be used in the definition is quite big and I prefer to keep it in a dedicated .m
file.
Does anyone know why I can't define a function using an Import
inside a module? Again, the problem exist in the Package only.
Thanks a lot in advance, and happy new year! :)
Ps: I apologize for the criptic title.
?? test`Private`f
- you'll see that thex
returned fromImport
is not in the same context asf
$\endgroup$test`Private`f[test`Private`x_]=x^2
. $\endgroup$testFun
, you are no longer in thetest`Private`
context, you are now in the global context. A quick fix is to modify the body offModule
to usef[ Global`x_] = ....
. This assumes that when you actually calltestFun
you will be in the global context. Someone else will have to provide a more robust solution. $\endgroup$BeginPackage
andEndPackage
inside theModule
. As an aside, usingModule[{}, ...]
is less efficient than just using(...)
. You're not usingModule
for scoping so you can drop it. $\endgroup$test
is just an example to explain the problem, in my code I really needModule
because I have several local variables. $\endgroup$