Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>ToExpression</code> uses the current binding of <code>$Context</code> when creating symbols, so you can force your expression to be interpreted within a particular context thus:</p> <pre><code>Block[{$Context="MyPackage`Private`"}, ToExpression[#][5]] &amp; /@ tests </code></pre> <p>I'm not sure I understand the circumstances of the original question. You can get the current context using <code>$Context</code> or <code>Context[]</code>... but <code>ToExpression</code> will automatically use the current context without intervention.</p> <p>If I run the exhibited code in a notebook, it works fine. If I run it like this:</p> <pre><code>Begin["MyPackage`Private`"] test1[g_] := (g == 5); test2[g_] := (g == 6); tests = {"test1", "test2"} ToExpression[#][5] &amp; /@ tests End[] </code></pre> <p>... it also works fine. I can get it to fail if I run it like this:</p> <pre><code>(* in the package file *) Begin["MyPackage`Private`"] test1[g_] := (g == 5); test2[g_] := (g == 6); End[] (* in the notebook *) tests = {"test1", "test2"} ToExpression[#][5] &amp; /@ tests </code></pre> <p>... which not only fails but also creates spurious symbols in the notebook's context. You can work around this problem using the <code>Block</code> recipe from above.</p> <p>If you want to capture the context that was in effect at the moment the package code was loaded, you can do something like this:</p> <pre><code>(* in the package *) Begin["MyPackage`Private`"] test1[g_] := (g == 5); test2[g_] := (g == 6); tests = {"test1", "test2"}; With[{context = $Context}, runTests[] := Block[{$Context = context}, ToExpression[#][5]] &amp; /@ tests ] End[] (* in the notebook *) MyPackage`Private`runTests[] </code></pre> <p><code>runTests</code> uses <code>With</code> to inject the private package context into its definition.</p> <p>As Janus' noted, it is better to use symbols than strings since they automatically manage the whole context issue -- but this assumes your actual use case will permit the use of symbols.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload