I am writing a package in which I have some constants defined inside a With block, which are then used by various functions defined inside that block.

Separate to this, I have an .mt file which contains tests for these various functions.

However, on occasion, I need access to those constants in my test file. Is there some way of referring to them directly rather than having to redefine them in my .mt file, which is what I am doing currently.

many thanks for your help

  • 3
    $\begingroup$ "local variables defined inside a With block" - they're not supposed to be seen from outside. Stuff that's intended to be seen outside shouldn't be defined within a With[]. $\endgroup$ – J. M.'s torpor May 22 '20 at 13:15
  • 4
    $\begingroup$ Define global variables inside that With block, assigning to them the values those constants have. You can do that conditionally using some variable like $debugMode to control that. You can have those variables private to your package (which will naturally happen if they are in the implementation part of the package). You will then be able to access those variables from outside. However, any need to access them from outside may indicate that perhaps you should make them generally globally accessible, or reconsider your design. $\endgroup$ – Leonid Shifrin May 22 '20 at 13:23
  • $\begingroup$ Something like this ? Cases[ImportString["With[{c = 42,g=9.81}, Block[{bla}, bla = const]]", "HeldExpressions"], With[a_List, __] :> Inactivate[a, Set], -1] // Flatten $\endgroup$ – Rolf Mertig May 22 '20 at 15:30
  • $\begingroup$ @J.M. - Yes, I understand that - but this is for testing purposes. How do you approach this problem when you are testing your own packages? $\endgroup$ – RobertNathaniel May 22 '20 at 17:10
  • $\begingroup$ @LeonidShifrin - Thanks. Simple enough for me to understand and quick enough for me to implement. $\endgroup$ – RobertNathaniel May 22 '20 at 17:13

Your Answer

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

Browse other questions tagged or ask your own question.