Skip to main content
3 of 6
added 668 characters in body
Mr.Wizard
  • 273.1k
  • 34
  • 595
  • 1.4k

I find this question rather enigmatic. As Nasser notes in a comment every Symbol has a context. You should be aware that Symbols are created during parsing. See: Local variables in Module leak into the Global context.

You also say "The following works" so I wonder why you are not using that. Perhaps you want:

SetAttributes[call, HoldAll];

call[file_String, function_, args___] :=
  Block[{$ContextPath, function}, Get[file]; function[args]]

Use would be:

call["test.m", test, "thing to print"]

thing to print

Note that the symbol Global`test is created as described in the linked Q&A above, but it is not defined.


On reflection, perhaps you just want to load definitions into a private context (e.g. test` ) that is not on the $ContextPath. That can be done like this:

Block[{$ContextPath = {"test`", "System`"}, $Context = "test`"}, Get["test.m"]]

This is essentially equivalent to BeginPackage but it works as a single line of code.

The defined function is then called with test`test:

test`test["thing 2"]

thing 2


Incorporating the last round of comments, you may find use in this function which combines that shown above and Leonid's method from Is it possible to use Begin and End inside a Manipulate?:

SetAttributes[runPrivate, HoldAllComplete];

runPrivate[code_] :=
  With[{body = MakeBoxes @ code},
    Block[{$ContextPath = {"runPrv`", "System`"}, $Context = "runPrv`"},
      ToExpression @ body]]

Now:

runPrivate[Get["test.m"]; a = 5; test[a]]

5

Global Symbols a and test remain undefined:

?a
?test

Global`a

Global`test

Mr.Wizard
  • 273.1k
  • 34
  • 595
  • 1.4k