Skip to content

is_nonstr_iter recognize 0-D numpy array as iterable #4001

@seisman

Description

@seisman

As shown below, a 0-D numpy array is recognized as iterable by the is_nonstr_iter function, but actually we can't loop over it.

In [1]: import numpy as np

In [2]: x = np.array(40)

In [3]: x.ndim
Out[3]: 0

In [4]: from pygmt.helpers import is_nonstr_iter

In [5]: is_nonstr_iter(x)
Out[5]: True

In [6]: from collections.abc import Iterable, Iterator

In [7]: isinstance(x, Iterable)
Out[7]: True

In [8]: [i for i in x]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[9], line 1
----> 1 [i for i in x]

TypeError: iteration over a 0-d array

In [9]: "/".join(x)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[10], line 1
----> 1 "/".join(x)

TypeError: can only join an iterable

So, a 0-D numpy array is iterable (has the __iter__ method) but is not an iterator (doens't have the __next__ method).

In [8]: isinstance(x, Iterator)
Out[8]: False

Because we usually need to loop over an iterable or join an iterable, perhaps we should use isinstance(x, Iterator) rather than isinstance(x, Iterable)?

Edit: isinstance([2, 3, 4], Iterator) returns False, so it doens't work.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions