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

59 Views Asked by At

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.

1

There are 1 best solutions below

2
lexotero On

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: