For setting attributes directly on int
itself and other built-in types (rather than their instances), this protection happens in type.__setattr__
, which specifically prohibits setting attributes on built-in types:
static int
type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
{
int res;
if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
PyErr_Format(
PyExc_TypeError,
"can't set attributes of built-in/extension type '%s'",
type->tp_name);
return -1;
}
...
Py_TPFLAGS_HEAPTYPE
is the flag that indicates if a type was defined in Python rather than C.
You cannot do the same thing with your own classes unless you implement them in C. You can sort of pretend to do it, by writing a metaclass with a custom __setattr__
, but that makes using other useful metaclasses more complicated, and it still doesn't prevent someone calling type.__setattr__
on your classes directly. (Trying a similar trick with object.__setattr__(int, ...)
doesn't work, because there's a specific check to catch that.)
You didn't ask about instances of built-in types, but they're also interesting. Instances of most built-in types can't have attributes set on them simply because there's nowhere to put such attributes - no __dict__
. Rather than having a special "no setting allowed" __setattr__
, or lacking a __setattr__
, they usually inherit __setattr__
from object
, which knows how to handle objects with no __dict__
:
descr = _PyType_Lookup(tp, name);
if (descr != NULL) {
Py_INCREF(descr);
f = descr->ob_type->tp_descr_set;
if (f != NULL) {
res = f(descr, obj, value);
goto done;
}
}
if (dict == NULL) {
dictptr = _PyObject_GetDictPtr(obj);
if (dictptr == NULL) {
if (descr == NULL) {
PyErr_Format(PyExc_AttributeError,
"'%.100s' object has no attribute '%U'",
tp->tp_name, name);
}
else {
PyErr_Format(PyExc_AttributeError,
"'%.50s' object attribute '%U' is read-only",
tp->tp_name, name);
}
goto done;
}
...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…