How to add a custom NumPy function to the original source code?

Viewed 357

To get a feel for NumPy's source code I want to start by adding my own dummy custom function. I've followed their docs to set up a developing environment and have done an inplace build of NumPy as advised ($ python setup.py build_ext -i; export PYTHONPATH=$PWD).

Now I want to add this function:

def multiplybytwo(x):
    """
    Return the double of the input
    """

    y = x*2

    return y

But I do not know where to place it so that this code would run properly:

import numpy as np

a = np.array([10])

b = np.mulitplybytwo(a)
3 Answers

This answer has been added at OP’s request.

As mentioned in my comments above, a starting point (of many) would be to investigate the top level __init__.py file in the numpy library. Crack this open and read through the various imports and initialising setup. This will help to get your bearings as to where the new function could be placed, as you’ll likely see from where other (familiar) top-level functions are imported.

Caveat:
While I’d generally discourage adding custom functionality to a library (as all changes will be lost on upgrade), I understand why you’re looking into this. Just keep in mind what is stated in previous sentence.

Everything in Python is an object!

So, you can add your function to NumPy in the same way you say that x = 1

See below:

>>> def multiplybytwo(x):
...     """
...     Return the double of the input
...     """
...     y = x*2
...     return y
>>> import numpy as np

>>> np.mulitplybytwo = multiplybytwo   ## HERE IS THE "TRICK"

>>> a = np.array([10])

>>> b = np.mulitplybytwo(a)

>>> b
array([20])

>>> print(b)
[20]

In that line, you are creating a custom function in NumPy and saying that that function is the one defined by you.

You can have a proof using id

>>> id(np.multiplybytwo)
140489045965856

>>> id(multiplybytwo)
140489045965856
>>>

Both id are the same.

Related