# How to load a package without naming conflicts?

This question applies to any package, but I encountered this problem while working with graphs. There are symbols in the Combinatorica package (such as Graph, IncidenceMatrix, EdgeStyle, and others) that have the same name as analogous symbols in System. If I execute Needs[Combinatorica], then I can access CombinatoricaGraph by the name Graph, but if I want to access SystemGraph, I have to write SystemGraph.

I want to use the Combinatorica prefix to access all the symbols in Combinatorica, and I want to access System symbols without using a prefix. And I don't want to have the symbols Graph, IncidenceMatrix, and so on, in red in Mathematica because of the naming conflict.

Is there a way to use the Combinatorica package without introducing naming conflicts?

-

Shadowing occurs only when there are two functions with the same name that are in $ContextPath. So right after you do <<Combinatorica, do the following: $ContextPath = Rest@$ContextPath;  What this does is that it removes Combinatorica (which is the package you just loaded). Now the only Graph function that's on the path is SystemGraph and you can call it simply by the name, without the prefix. To access any functions from the package, use the prefix, as CombinatoricaGraph. If Combinatorica was loaded a while ago and you have loaded other packages in between, Rest@... is not going to be helpful. In that case, use: $ContextPath = DeleteCases[$ContextPath, "Combinatorica"];  - The answer of @R.M. already explains the essence of the problem. You can streamline the process of removing the Combinatorica from the $ContextPath by loading it via

Block[{$ContextPath}, Needs["Combinatorica"]]  (or use Get intead of Needs, although Needs is a preferred way to load a package). In this way, you don't have to do anything afterwards, since, once the scope of Block is left, the $ContextPath automatically is reset to its previous value.

This is a generally useful trick to load packages without adding them to the \$ContextPath. I found it quite useful on many occasions.

-
Here's something that's good to be aware of (see under P.S.) If using Combinatorica, there's a chance one might one to use the ToCombinatoricaGraph function as well. –  Szabolcs Apr 21 '13 at 2:34

One way is to use something like Graph=SystemGraph; and use Graph which refers to SystemGraph thereafter. You can use any other name such as g=SystemGraph as well. The downside is that you have to do it for any function.

Edit: This does the trick:

rep = StringReplace[#, "System" -> ""] &;
Scan[
Unprotect[#]; ToExpression[# <> "=System" <> #]; Protect[#]; &,
Intersection[
rep /@ Names["Combinatorica*"],
rep /@ Names["System*"]
]
]

-
You don't have to do the rep /@ Names["Combinatorica*"] part, you know... –  Guess who it is. May 15 '12 at 3:55