The problem is that if you pass a symbol, it will be created already during the parsing stage, when you pass it, in the current context. Therefore I suggest to pass its string name instead. This function will do the job:
ClearAll[f];
f[symbolName_String, value_, context_] :=
Block[{$ContextPath},
BeginPackage[context];
ToExpression[
symbolName,
StandardForm,
Function[name, Set[name, value], HoldAll]
];
EndPackage[]
]
for example
f["a", 10, "Test`"]
Test`a
(* 10 *)
If you still want to pass a symbol, you can use this:
ClearAll[f];
f[symbol_, value_, context_] :=
With[{set = MakeBoxes[symbol = value]},
Block[{$ContextPath},
BeginPackage[context];
ReleaseHold[MakeExpression@set];
EndPackage[]]];
which is a version of the code I used herehere. But be aware that you will also create the symbol symbol
in the current working context, so you may additionally use Remove
to remove it.
So, for example:
f[a, 20, "Test`"]
Test`a
(* 20 *)