See how the native functions were written - Python

2

Is there a practical way to check, as the code for a Python function is written, max() ?

    
asked by anonymous 01.08.2018 / 20:30

2 answers

8

When a function is written in Python, you can use the inspect .

For example:

def somar(a, b):
    return a + b

When doing print(inspect.getsource(somar)) you will have the output as string :

def somar(a, b):
    return a + b

This will work for modules, classes, methods, functions, and others; only will not work for objects that have been implemented in C, such as sys module and min and max functions. To do so, you'll need to look at the source files, official repository .

If the intention is to thoroughly analyze what happens, I suggest using the module dis . With it you can, for example, check the opcode that will be executed by the interpreter:

>>> print( dis.dis(somar) )
  2           0 LOAD_FAST                0 (a)
              2 LOAD_FAST                1 (b)
              4 BINARY_ADD
              6 RETURN_VALUE
None

What each command means you can read in the documentation.

    
01.08.2018 / 20:41
3

All Python source code (default implementation) is in Github and can be browsed. The max() function

    
01.08.2018 / 20:37