# Function that assigns properties [duplicate]

I want to create a function that creates and assigns properties to a symbol. In theory this would behave similarly to the NonzeroValues property of SparseArrays.

Here's what I currently have, and where I'd like to go.

func[x_] := Module[{data},
(*data=Import data from source based on x*)
HoldPattern[func[x, "Length"]] = Length@data;
HoldPattern[func[x, "Dimensions"]] = Dimensions@data;
]

func[15,"Length"]


225

However, I'd like this to work more like this:

var=func[15];

var["Length"]


225

It would be ideal not to have to calculate this every time a property is retrieved. For efficiency sake, importing the data every time a property is retrieved isn't feasible.

How so I define these subvalues at the first function call and store them for fast retrieval later?

-

## marked as duplicate by Ajasja, István Zachar, Michael E2, m_goldberg, bobthechemistFeb 23 at 2:42

I like to use properties like those in SparseArray and I find subvalues very useful for defining and accessing them. This is best used with a dummy head. The following is some code pulled out from one of my packages and modified. I've defined func here to be a minimal example of what your actual function might look like.

Clear[func, myHead]
func[str_] := With[{img = ExampleData[{"TestImage", str}]},
"Image" -> img, "ImageDimensions" -> ImageDimensions@img,
"ImageColorSpace" -> ImageColorSpace@img
}]
];

myHead[list_]["Properties"] := list /. Rule[field_, _] :> field

I like using Format to control the display and provide just a short summary (I just show the length of the list here, but you can change it to whatever you want), so that accidentally displaying it will not make the FE hang if it happens to contain large lists. You can also use it as a deliberate way to get a quick summary.