0

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?

5
  • 3
    Cpython implementation has a repository on github Commented Aug 22, 2016 at 12:26
  • Actually, the oficial one is on hg.python.org Commented Aug 22, 2016 at 12:59
  • @TimFuchs yeah, but the github one is easier to browse, and is mostly kept in sync Commented Aug 22, 2016 at 13:08
  • 1
    Your image of text isn't very helpful. It can't be copied into an editor, and it doesn't index very well, meaning that other users with the same problem are less likely to find the answer here. Please edit your post to incorporate the relevant text directly (preferably using copy+paste to avoid transcription errors). Commented Aug 22, 2016 at 13:32
  • Looks like you're using PyCharm or something to view the definition - obviously this isn't the real one. Commented Aug 22, 2016 at 14:25

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.