3

When using numpy, often times one can choose between calling a function from the numpy API, and calling the function from the ndarray, e.g.:

>>> import numpy as np
>>> array_ = np.array([True, False, True])
>>> np.any(array_)
True
>>> array_.any()
True

Functionally these seem identical to me; Are they? Are they programmatically different? (e.g. performance/memory wise)

I tried finding the answer in the numpy reference manual about ndarrays and routines, but as far as I can tell no explanation is given.

1
  • Well if you perform a some_array.foo, then in case foo is not attached to the some_array, it will fallback to numpy.foo(array(some_array)). Commented Jul 12, 2018 at 13:07

1 Answer 1

2

One note on terminology first so the rest of this example is clear--np.any(arr) is a function; arr.any() is technically an instance method.


Generally, the top-level np.<function>(arr) functions are wrappers around the methods for arr.

Here's the source for np.any(), NumPy version 1.14.5, from numpy.core.fromnumeric:

def any(a, axis=None, out=None, keepdims=np._NoValue):
    arr = asanyarray(a)
    kwargs = {}
    if keepdims is not np._NoValue:
        kwargs['keepdims'] = keepdims
    return arr.any(axis=axis, out=out, **kwargs)

Other versions of NumPy (such as the one currently on GitHub) may use a "wrapper factory function" that does virtually the same thing. See also this Q/A for a similar example with np.transpose(). Generally what it boils down to is np.<function>(arr) becomes some form of getattr(arr, <function>), at least for the stuff in fromnumeric.py.


In terms of a comparison--you're talking about an incremental amount of additional overhead when using the top-level function, but that comes with some added flexibility: for instance, there's a call to np.asanyarray(a), which means you could pass a Python list as a to the function. On my computer, the call to np.asanyarray(arr) takes 1/8 the time of arr.any(), so to inject a bit of opinion into the answer, choosing between the two is probably not the first place to look in terms of performance optimization.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.