7
$\begingroup$

I'm working on a package and I want it to (usually) print a welcome message when it's loaded, primarily to leave a written trace of the version number in the notebook where it's used. For example:

BeginPackage["Test`"];
Test::usage="Testing";
Begin["`Private`"];
Print["Test Package Version 1.0"];
Test:=Print["123"];
End[];
EndPackage[];

<<Test`
(* Test Package Version 1.0 *)

However this gets cumbersome in the documentation pages I'm writing, so I'd like a way to omit the welcome message. Maybe with a semicolon, as:

Needs["Test`"];
(* silently loads package *)

However, the Print inside the package doesn't care if Needs has a semicolon or not. Is there some straightforward way to achieve this effect?

$\endgroup$
  • 2
    $\begingroup$ Instead of Print your could just return your string after EndPackage[]. $\endgroup$ – Kuba Jun 18 at 8:46
  • $\begingroup$ @Kuba Thanks, I suspected there might be an easy way. I'd tried including the string, but not after EndPackage[]. $\endgroup$ – Chris K Jun 18 at 8:49
  • $\begingroup$ @Kuba Have you ever used this in practice? I'd like to read opinions about how well it works in practice. I never thought of this solution, but it looks to be very useful. $\endgroup$ – Szabolcs Jun 18 at 8:51
  • $\begingroup$ @Szabolcs It seems to work for me so far. $\endgroup$ – Chris K Jun 18 at 8:54
  • $\begingroup$ @Szabolcs I didn't have a use case for such message. Otoh the fewer side effects package loading has the better. Atm I don't see where this can lead to a problem. $\endgroup$ – Kuba Jun 18 at 8:56
9
$\begingroup$

Moving my comment to the answer: you can put your message after EndPackage[] instead of printing it:

BeginPackage["Test`"];
  Test::usage="Testing";
Begin["`Private`"];    
  Test:=Print["123"];
End[];
EndPackage[];
"Test Package Version 1.0"

It seems to do exactly what you want.

$\endgroup$
  • 3
    $\begingroup$ Reference from the documentation for Get: "<<name reads in a file, evaluating each expression in it and returning the last one." $\endgroup$ – Michael E2 Jun 18 at 22:50

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.