Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can non-built-in type instances be immutable in python?

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.

like image 917
to7m Avatar asked Feb 22 '26 00:02

to7m


1 Answers

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._DTypeMeta is defined here https://github.com/numpy/numpy/blob/a115ed3a3c92d8607c5eaa38a98825ac8a5e1bfc/numpy/core/src/multiarray/dtypemeta.c#L964
  • The immutable flag (i.e. Py_TPFLAGS_IMMUTABLETYPE) is not explicitly applied, but...
  • PyType.Ready() automatically applies the Py_TPFLAGS_IMMUTABLETYPE - https://docs.python.org/3/c-api/typeobj.html#c.Py_TPFLAGS_IMMUTABLETYPE
  • numpy._DTypeMetadata type is thus immutable.
like image 158
lexotero Avatar answered Feb 24 '26 16:02

lexotero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!