简体   繁体   中英

implemention of python builtin function

I'm a freshman in python and I want to study the implemention of python's builtin function like abs() , but in the python file of \\__builtin__.py I saw this:

Builtin_abs_function

Does anybody know how it works?

The built-in functions are implemented in the same language as the interpreter, so the source code is different depending on the Python implementation you are using (Jython, CPython, PyPy, etc). You are probably using CPython, so the abs() function is implemented in C. You can look at the real source code of this function here .

static PyObject *
builtin_abs(PyObject *module, PyObject *x)
{
    return PyNumber_Absolute(x);
}

The source code for PyNumber_Absolute (which is, arguably, more interesting) can be found here :

PyObject *
PyNumber_Absolute(PyObject *o)
{
    PyNumberMethods *m;

   if (o == NULL)
        return null_error();
    m = o->ob_type->tp_as_number;
    if (m && m->nb_absolute)
        return m->nb_absolute(o);

    return type_error("bad operand type for abs(): '%.200s'", o);
}

As you can see, the actual implementation of abs() calls nb_absolute() which is different for different object types. The one for float looks like this

static PyObject *
float_abs(PyFloatObject *v)
{
    return PyFloat_FromDouble(fabs(v->ob_fval));
}

So, effectively, CPython is just using the C math library in this case. The same will be true for other implementations of Python - Jython is using the functions from the Java math library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM