MASBHA NOMAN
MASBHA NOMAN

Reputation: 198

how to print source code of a builtin module in python?

I want to print the source code of a built-in method. for example, math is a built-in module of python and i want to print the source code of ceil

i know how to print the source code of a custom module using inspect.getsource

need help
I am trying to create a programme where i can call any builtin methods or functions and it will display only the source code of that function or module.
Python has almost everything in builtin library, i want to use these libraries

example:

input: factorial
output:
        def factorial(n):
            if n == 0:        
                return 1      
            else:      
                return n * factorial(n-1)

works just fine
import inspect
inspect.getsource(factorial)
doesn't work ... results in Type Error
import inspect
import math
print(inspect.getsource(math.ceil)
TypeError: <built-in function ceil> is not a module, class, method, function, traceback, frame, or code object

thanks in advance :)

Upvotes: 0

Views: 9261

Answers (1)

Paulo Scardine
Paulo Scardine

Reputation: 77251

If the source is Python you can do this:

import inspect
import math

try:
    print(inspect.getsource(math))
except OSError:
    print("Source not available, possibly a C module.")

As other people already commented, many builtin modules are C. If it is the case you will have to dive in the source - fortunately it is not that hard to find, the structure is quite intuitive.

For math.ceil the source code is at line 1073 of Modules/mathmodule.c in cpython:

/*[clinic input]
math.ceil
    x as number: object
    /
Return the ceiling of x as an Integral.
This is the smallest integer >= x.
[clinic start generated code]*/

static PyObject *
math_ceil(PyObject *module, PyObject *number)
/*[clinic end generated code: output=6c3b8a78bc201c67 
input=2725352806399cab]*/
{
    _Py_IDENTIFIER(__ceil__);
    PyObject *method, *result;

    method = _PyObject_LookupSpecial(number, &PyId___ceil__);
    if (method == NULL) {
        if (PyErr_Occurred())
            return NULL;
        return math_1_to_int(number, ceil, 0);
    }
    result = _PyObject_CallNoArg(method);
    Py_DECREF(method);
    return result;
}

Upvotes: 6

Related Questions