pythonnumpysource-code-protection

how can you retrieve source code in python, inspect gives type error


In order to get better at programming, analysing numpy and scipy's source code could come in handy.

import inspect,numpy as np

x = [1,2]
inspect.getsource(np.max(x))

gives TypeError

please help,kind regards


Solution

  • For numpy and scipy code, check the official documentation.

    https://numpy.org/doc/stable/reference/generated/numpy.amax.html

    Often these have a [source] link. Or it running ipython, just using np.max?? gives the same thing.

    In this case, most of the display is the docs, and the actual code is short:

    def amax(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
             where=np._NoValue):
        return _wrapreduction(a, np.maximum, 'max', axis, None, out,
                              keepdims=keepdims, initial=initial, where=where)
    File:      /usr/local/lib/python3.6/dist-packages/numpy/core/fromnumeric.py
    

    This tells us that np.max (or amax) delegates the action to a similarly name max method. And if we dig further we see that the method is built-in, that is, it is compiled code that we cannot readily read. This is a rather common situation in numpy. Functions delegate to similarly named methods. Unless you are prepared to do some serious reading of c code, this is as far as you'll get. And as far as you need to go, unless you want to be numpy developer/contributor.