EDIT
This issue is specifically different from the "duplicate" question. The creation of variables in the active context during parsing is of no surprise and is the expected behavior.
What I'm observing is the creation of a temporary variable which is not automatically deleted. The following constructs:
f[x_] := With[{a = x}, dostuff];
or more generally
f[x_] := Module[{a = g[x]}, dostuff];
create not only a
in the global namespace, but also a$
:
?a$
Global`a$ Attributes[a$] = {Temporary}
Should I be concerned, is this a memory leak, is there specific reasoning behind this, etc?
END EDIT; original question below
Starting with a fresh kernel I type:
myFunc[x_] := With[{g = x}, Print[5]];
? Global`*
Among the returned symbols I find, not only the expected myFunc
, g
, and x
. There is also the temporary in attribute g$
. Why is this happening? Is this indicating some sort of memory leak?
The implicit question is also "how to avoid this and keep my packages clean if this is indeed the case".
m_goldberg asked for a more realistic use case; I'm more than happy to oblige:
ImportBIG[names_List, p0_Real, a0_Real, depol_Real, fourierFunc_]:=
With[
{strm = OpenRead[#, BinaryFormat->True] & /@ names , n = Length[names],
fft = (Exp[2 I a0 Degree - 2 I Pi (-1+(ConstantArray[0.I,20]+Range[20]))2/20])/20
},
Block[{...},
Do[assoc[idx] = ReadString[strm[[idx]]];
dostuff;, {idx, n}]
(* more do loops with {idx, n} *)
Do[assoc[idx, "Rho"] = With[{f = assoc[idx, "Fourier"]},
ArcTan[-I Sqrt[1 - 4 Abs[f]^2] + 2 Im[f]] / (1 - 2 Re[f])]], {idx, n}]
]
]
As you can see, I'm using With
as an idiomatic way to have constants in my functions, also to shorten on keystrokes to make code more readable, to cut down on repeated evaluation of the same thing (such as Length[names]
), etc.
In this case, of course, the offending temporary variables are n$
, fft$
, strm$
and f$
.
x
in your case) have semantics very close to whatWith
provides and I don't see why you need to useWith
like you show in your question. $\endgroup$With[{x = 5}, Function[x, x^2]]
where one of the twox
s must be renamed to prevent conflict between theWith
and theFunction
. In your example this doesn't seem to be needed but happens anyway. That's much better than when it is needed but doesn't happen. It doesn't cause harm. I don't know why theTemporary
isn't removed (as it is withModule
ones), but it has been like this forever. $\endgroup$var$
has no value. It's not causing any problems. It doesn't produce an unlimited amount of pollution like numberedModule
variables would since the name is always the same:var$
, instead ofvar$1
,var$2
,var$3
... with no end to it. While the question can be interesting theoretically, I see no practical issues. $\endgroup$