Why can python bulit-in functions like sum (), max (), min () be used to calculate the numpy ndarray type?

I am learning numpy. But I had some questions that confused me:

>>> import numpy as np >>> a = np.arange(10) >>> a.sum() 45 

and: sum(a) give the same result. So why an inline function can support data type calculation from a third-party library? min () and max () do the same. (When dim is 1)

I have two guesses about this, I prefer the latter:

  • python core developer adds ndarray support;
  • some hidden attributes define in ndarray for this to happen. (If so, what is it?)
+5
source share
1 answer

All types of third-party libraries must execute, implements the expected protocol (sometimes also called an interface). sum() function documentation tells you what is expected:

Runs the sums and iterative elements from left to right and returns the total value.

min() and max() set similar requirements (return the smallest element in iterable, return the largest element in iterable).

Here iterable is the protocol described in the standard documentation . Protocols themselves are not types, they are just a set of methods that are expected to behave in a certain way. The collections.abc module provides several objects that you can use to check if something implements the protocol:

 >>> import numpy as np >>> from collections.abc import Iterable >>> a = np.arange(10) >>> isinstance(a, Iterable) True 

So the ndarray type is ndarray and that the sum() function uses to get all the values ​​contained in the array, summing these values ​​up for you.

Because Python relies on protocols, core language developers do not need to add support for each third-party library. Instead, libraries simply live up to the expectations of the main language.

Note that the ndarray.sum() implementation may use an internal type implementation; it can most likely produce the amount faster, since it does not need to convert the internal data into Python objects first (in this case, the iteration returns nested types, Python int objects, while the internal representation contains C integers).

+7
source

Source: https://habr.com/ru/post/1260504/


All Articles