12
$\begingroup$

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`"]

$\endgroup$
11
$\begingroup$

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 *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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