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.

After calling some functions, if I look into $ContextPath, I can see that JLink` is in there. Is there a way to find out what sequence of functions calls (like a stack-trace) imported a particular package?

Something like FuncA called FuncB which called FuncD which executed Needs["JLink`"]

share|improve this question

1 Answer 1

up vote 10 down vote accepted

Well, here is a suggestion: you can overload Needs using Villegas-Gayley trick. To do this safely, here is a generator for local environments, where Needs will be overloaded:

createTraceEnvironment[context_String]:=
    Module[{inNeeds},
        Function[                
            code,
            Internal`InheritedBlock[                    
                {Needs},                    
                Unprotect[Needs];
                Needs[context]/;!TrueQ[inNeeds]:=
                    Block[{inNeeds=True},
                        Print[Stack[_][[3;;-5]]];Needs[context]
                    ];
                Protect[Needs];
                code
            ],
            HoldAll
        ]
    ];

Now here is how it can be used: first create a local environment for "JLink`":

env = createTraceEnvironment["JLink`"];

Now it can be used, for example:

env[Needs["DatabaseLink`"]]
{
    Needs[DatabaseLink`],
    <<DatabaseLink`,
    <<DatabaseLink`DatabaseLink`;, 
    <<DatabaseLink`DatabaseLink`, Get[ToFileName[/Applications/Mathematica_10_Sep_26_2013.app/SystemFiles/Links/DatabaseLink/Kernel,DataSources.m]];Get[ToFileName[/Applications/Mathematica_10_Sep_26_2013.app/SystemFiles/Links/DatabaseLink/Kernel,SQL.m]];,
    <</Applications/Mathematica_10_Sep_26_2013.app/SystemFiles/Links/DatabaseLink/Kernel/SQL.m,
    Needs[JLink`];
 }

But loading packages (or executing other code) which load "JLink`", without the local environment, will go as usual. For example, RLink also loads JLink, but here nothing is printed:

Needs["RLink`"] 

(* Null *)
share|improve this answer

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.