Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Some programming languages offer the possibility of importing a single function from a library, as in

from x import y

I'm looking to import only one function (GraphCoordinates) from the GraphUtilities package.

The following commands do not work:

<< GraphUtilities`GraphCoordinates

Needs["GraphUtilities`", "GraphCoordinates"]

The former gives an error, while the latter loads the entire GraphUtilities package.

How should I proceed?

share|improve this question
add comment

1 Answer 1

up vote 7 down vote accepted

A version of this question has been asked before on StackOverflow. You can look at the answers there for some options. To summarize, Mathematica currently does not natively support such a fine-grained encapsulation, which would certainly be a nice thing to have (IMO).

One simple thing you can do is to load the entire package via

Block[{$ContextPath}, Needs["GraphUtilities`"]]

(see this answer for an explanation), and then refer to your function by its long name:

GraphUtilities`GraphCoordinates

You can then go further and create an alias in your current context, if you don't want to type the long name:

GraphCoordinates = GraphUtilities`GraphCoordinates

Since the loaded package is not on the $ContextPath, this will not lead to shadowing. Note however that such aliases will work most of the time, but not always.

This workaround should work fine if you are ok to load the entire package and just don't want all its public functions to become public in your current context ("Global`",or whatever it is). If you truly want to avoid even loading the entire package, you are (currently) out of luck.

share|improve this answer
    
Bleh! This is what I feared... Since I found nothing in the official documentation. Thanks for the hack! –  CHM Aug 10 '12 at 19:56
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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