If I try to run
import numpy as np
type(np.dtype).moo = 7
then I get
TypeError: cannot set 'moo' attribute of immutable type 'numpy._DTypeMeta'
which I can't find an explanation for.
numpy._DTypeMeta is a type instance, so this should be roughly equivalent to
type.__setattr__(numpy._DTypeMeta, "moo", 7)
So what is happening in type.__setattr__ that detects numpy._DTypeMeta should be immutable?
I could imagine that immutable built-ins such as float, might be stored in a specific place in logical memory, and that type.__setattr__ could check for that, but numpy isn't built-in.
This is an interesting question, and I'm curious to see an answer from someone with a better understanding of the C API.
Here is my quick incomplete (and probably incorrect) take:
numpy._DTypeMetais defined here https://github.com/numpy/numpy/blob/a115ed3a3c92d8607c5eaa38a98825ac8a5e1bfc/numpy/core/src/multiarray/dtypemeta.c#L964Py_TPFLAGS_IMMUTABLETYPE) is not explicitly applied, but...PyType.Ready()automatically applies thePy_TPFLAGS_IMMUTABLETYPE- https://docs.python.org/3/c-api/typeobj.html#c.Py_TPFLAGS_IMMUTABLETYPEnumpy._DTypeMetadatatype is thus immutable.