Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are built-in types protected from overwriting (assigning to) their methods?

I noted that

int.__str__ = lambda x: pass

yields an error.

I can see, why that is forbidden. But how? Can I use that in "normal" code?

like image 653
steffen Avatar asked May 01 '18 14:05

steffen


1 Answers

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;
    }
    ...
like image 70
user2357112 supports Monica Avatar answered Nov 03 '22 23:11

user2357112 supports Monica