[Numpy-discussion] numpy all unexpected result (generator)

Dag Sverre Seljebotn d.s.seljebotn at astro.uio.no
Tue Jan 31 10:46:01 EST 2012


On 01/31/2012 04:35 PM, Benjamin Root wrote:
>
>
> On Tue, Jan 31, 2012 at 9:18 AM, Robert Kern <robert.kern at gmail.com
> <mailto:robert.kern at gmail.com>> wrote:
>
>     On Tue, Jan 31, 2012 at 15:13, Benjamin Root <ben.root at ou.edu
>     <mailto:ben.root at ou.edu>> wrote:
>
>      > Is np.all() using np.array() or np.asanyarray()?  If the latter,
>     I would
>      > expect it to return a numpy array from a generator.
>
>     Why would you expect that?
>
>     [~/scratch]
>     |37> np.asanyarray(i>5 for i in range(10))
>     array(<generator object <genexpr> at 0xdc24a08>, dtype=object)
>
>     --
>     Robert Kern
>
>
> What possible use-case could there be for a numpy array of generators?
> Furthermore, from the documentation:
>
> numpy.asanyarray = asanyarray(a, dtype=None, order=None, maskna=None,
> ownmaskna=False)
>       Convert the input to an ndarray, but pass ndarray subclasses through.
>
>       Parameters
>       ----------
>       a : array_like
> *Input data, in any form that can be converted to an array*.  This
>           includes scalars, lists, lists of tuples, tuples, tuples of
> tuples,
>           tuples of lists, and ndarrays.
>
> Emphasis mine.  A generator is an input that could be converted into an
> array.  (Setting aside the issue of non-terminating generators such as
> those from cycle()).

Splitting semantic hairs doesn't help here -- it *does* return an array, 
it just happens to be a completely useless 0-dimensional one.

The question is, is the current confusing and less than useful? (I vot 
for "yes"). list and tuple are special-cased, why not generators (at 
least to raise an exception)

Going OT, look at this gem:

????

In [3]: a
Out[3]: array([1, 2, 3], dtype=object)

In [4]: a.shape
Out[4]: ()

???

In [9]: b
Out[9]: array([1, 2, 3], dtype=object)

In [10]: b.shape
Out[10]: (3,)

Figuring out the "???" is left as an exercise to the reader :-)

Dag Sverre



More information about the NumPy-Discussion mailing list