1
$\begingroup$

In many cases I need to copy the Global` symbols foo into Module/Block, and to memory the meanings of the copies I named them as fooTemp before. For example,

f[foo_]:=Module[{fooTemp},
  fooTemp=foo;
  foo...
  fooTemp...
]

My question is that is it safe to name fooTemp as foo$? ref/message/Module/dups says "It is recommended that names of this form be avoided."

I tried the simple cases like

x = 1;
f := Print["value of x: ", x];

Module[{x$},
 {x, x$} // Print;
 ]
(*{1,x$40193}*)

Module[{x, x$},
 {x, x$} // Print;
 ]
(*Module::dups: Conflicting local variables x and x$ found in local variable specification {x,x$}.*)

Block[{x, x$},
 {x, x$} // Print;
 f
 ]; f
(*
{x,x$}
value of x: x
value of x: 1
*)

and these are expected from the scopings of Module/Block.

Are there other subtlties besides Module::dups if naming local variables ending with "$", say nested scoping constructs?


It seems that foo$$ is a better choice?

Module[{x, x$$},
 {x, x$$} // Print;
 ]
(*{x$48058,x$$$48058}*)

Module[{x$, x$$},
 {x$, x$$} // Print;
 ]
(*{x$48060,x$$$48060}*)

Interestingly Module[{x$$, x$$$},] will report Module::dups once again.

$\endgroup$
6
  • 2
    $\begingroup$ I know this isn't safe: func[s_] := Module[{foo}, foo = s]; func[foo$] because Module[{foo},...] renamesfoo to foo$; execute func[foo$] // Tracefoo$$ is probably not a good choice, either. That's the renaming convention used by DynamicModule[{foo},...], which may be renamed again by the Front End. If you know what you're doing, you can possibly get away with it. $\endgroup$
    – Michael E2
    Jun 30 at 0:01
  • 2
    $\begingroup$ Another comment is that this "need" arising "in many cases" seems strange to me. There are common use-cases like Block[{$MaxExtraPrecision = 500},...] in which global parameters are temporarily reset, but one doesn't need to put a $ at the end. You could put a non-ASCII character at the end, like ¢ (option-4 on my Mac) or § (option-6), if you want to keep a simple renaming convention. $\endgroup$
    – Michael E2
    Jun 30 at 0:16
  • 2
    $\begingroup$ "is it safe?" - I'm puzzled by your question: the system specifically gives you a warning and recommends against it! I'd stay away from it, out of an abundance of caution if nothing else... $\endgroup$
    – MarcoB
    Jun 30 at 0:54
  • $\begingroup$ @MichaelE2 Thanks for the examples! I have customized option+xx to other usages. Now I use $$foo as local variables. $\endgroup$
    – lilyric
    Jul 6 at 2:18
  • $\begingroup$ @MarcoB Yes, I agree. But for myself these questions are exercises to get better understanding of low-level things. $\endgroup$
    – lilyric
    Jul 6 at 2:24

0

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.