Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    }
    ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...