Here's a method you could use if you really want to directly modify your association yourself. To do that, you need to store the association in a variable and use Hold
attributes to prevent it from evaluating. In your case, it seems like it's easiest to just make MyData
HoldFirst
:
SetAttributes[MyData, HoldFirst]
You can now define your function as:
foo[MyData[data_Symbol?AssociationQ]] := (
data["extraField"] = 1;
MyData[data]
);
The AssociationQ
pattern test will ensure that the symbol data
refers to an association. You can use the function like so:
actualData = <|"bigArray" -> {{}}|>;
foo[MyData[actualData]]
actualData
Out[15]= MyData[actualData]
Out[16]= <|"bigArray" -> {{}}, "extraField" -> 1|>
Note that MyData[actualData]
does not show the association because of the HoldFirst
attribute. You could define custom formatting rules to make it show a preview of the data. You could also try to turn MyData
into a sort of constructor that will automatically create a new symbol to hold an association for you. For example:
ClearAll[MyData]
SetAttributes[MyData, HoldFirst]
MyData[stuff : Except[_Symbol]] := With[{
evaluatedStuff = stuff
},
Module[{storeVar = evaluatedStuff},
MyData[storeVar]
] /; AssociationQ[evaluatedStuff]
];
MyData[AssociationThread[Range[10], RandomReal[1, 10]]]
First[%]
MyData[storeVar$6198]
<|1 -> 0.236334, 2 -> 0.354161, 3 -> 0.314371, 4 -> 0.738186,
5 -> 0.916299, 6 -> 0.0289776, 7 -> 0.831803, 8 -> 0.533609,
9 -> 0.316124, 10 -> 0.211526|>
All of this is roughly how Association
itself actually works. Note the attributes on Association
:
In[29]:= Attributes[Association]
{HoldAllComplete, Protected}
This is what is meant when people say that Association
is a constructor and a container. You can tell that some sort of construction step takes place when you define an association:
Unevaluated[<||>] === <||>
False
dict[key]=key->value
) and store dictionary globally? $\endgroup$ – M.Z. May 7 '19 at 19:54SomeSymbol[data...]
very useful and I wanted to keep using this simple approach. But thanks for the suggestion. $\endgroup$ – Picaud Vincent May 7 '19 at 19:57