1
$\begingroup$

I have some shadowed symbols. How do I list all the contexts that they are in?

For instance, consider symbol x which is in contexts: package1, package2

BeginPackage["package1`"];
x["package"] := "package1";
EndPackage[];
BeginPackage["package2`"];
x["package"] := "package2";
EndPackage[];

attempt 1:

Information does not return package1`

enter image description here

attempt 2:

Names does not return package2`

In[1]:= Names["pa*`x"]
Out[1]= {package1`x,x}
$\endgroup$

2 Answers 2

5
$\begingroup$
Context /@ Names["pa*`x"]

In your "attempt 2", Names actually does include package2. When displaying symbols, the context is usually suppressed. It's shown if necessary for disambiguation. So, the plain x in the output is actually the x in the package2 context. Why is package1 explicit and package2 suppressed? Because of the context path:

$ContextPath
`{"package2`", "package1`", "System`", "Global`"}`

Since package2 was created after package1, it comes before package1 on the context path (we're pushing new contexts onto the front of the context path). If you were to reverse the package definitions, you would see package1 suppressed and package2 explicit.

$\endgroup$
1
  • $\begingroup$ Great answer, thanks! $\endgroup$ Feb 22 at 14:16
2
$\begingroup$

Expanding on @lericr's answer:

The trouble with Names["p*`x"] is that you have to know the first letter of the possible contexts.

A better approach is to search amongst the packages in $ContextPath.

In[1]= $ContextPath
Out[1]= {package2`,package1`,System`,Global`} 

          
 
In[3]:= DeleteCases[(Context/@ Names["*`x"]),a_/;!StringMatchQ[a,Alternatives["package1`","package2`","Global`","System`"]]]
Out[3]= {Global`,package1`,package2`}

Rolling up into one function:

contextsOfSymbol[symbol_] := DeleteCases[
                                        (Context /@ Names["*`" <> ToString[symbol]])
                                      , a_ /; ! StringMatchQ[a, Alternatives @@ $ContextPath]
                             ];

demo:

In[4]:= contextsOfSymbol[x]
Out[4]= {Global`,package1`,package2`}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.