[Python-Dev] Clean way in python to test for None, empty, scalar, and list/ndarray? A prayer to the gods of Python

Robert Kern robert.kern at gmail.com
Fri Jun 14 22:20:50 CEST 2013


On 2013-06-14 21:03, Brett Cannon wrote:
>
> On Fri, Jun 14, 2013 at 3:12 PM, Martin Schultz <maschu09 at gmail.com
> <mailto:maschu09 at gmail.com>> wrote:

>       - add a `size` attribute to all objects (I wouldn't mind if this is None
>     in case you don't really know how to define the size of something, but it
>     would be good to have it, so that `anything.size` would never throw an error
>
> This is what len() is for. I don't know why numpy doesn't define the __len__
> method on their array types for that.

It does. It gives the size of the first axis, i.e. the one accessed by simple 
indexing with an integer: some_array[i]. The `size` attribute givens the total 
number of items in the possibly-multidimensional array. However, one of the 
other axes can be 0-length, so the array will have no elements but the length 
will be nonzero.

[~]
|4> np.empty([3,4,0])
array([], shape=(3, 4, 0), dtype=float64)

[~]
|5> np.empty([3,4,0])[1]
array([], shape=(4, 0), dtype=float64)

[~]
|6> len(np.empty([3,4,0]))
3

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



More information about the Python-Dev mailing list