Skip to content

NumPy 1.21 __array_interface__ behavior #1173

@mwtoews

Description

@mwtoews

NumPy 1.21 has a new behavior described in this release note:

Exceptions will be raised during array-like creation: When an object raised an exception during access of the special
attributes __array__ or __array_interface__, this exception was usually ignored. A warning is now given when the exception is anything but AttributeError. To silence the warning, the type raising the exception has to be adapted to raise an AttributeError.

Shapely<2.0 versions still have a __array_interface__ property for most (all?) geometry types, and some of them, e.g. Polygon raise NotImplementedError("A polygon does not itself provide the array interface. Its rings do."). This is problematic with this example:

import numpy as np
import warnings
from random import random
from shapely.geometry import Polygon
warnings.filterwarnings('always')

geoms = [Polygon((random(), random()) for _ in range(3)) for _ in range(3)]
arr = np.empty(len(geoms), dtype=object)
arr[:] = geoms

which will show this message three times (one for each geometry)

<stdin>:1: DeprecationWarning: An exception was ignored while fetching the attribute __array_interface__ from an object of type 'Polygon'. With the exception of AttributeError NumPy will always raise this exception in the future. Raise this deprecation warning to see the original exception. (Warning added NumPy 1.21)

This is also an issue for GeoPandas, which will flood a terminal with warnings for large GeoSeries.

One very quick fix is to change the exception raised by Polygon.__array_interface__ to AttributeError. Other geometries may also need to be adjusted, but the BaseGeometry class should still raise NotImplementedError. If this seems reasonable, I can prepare a PR for 1.8.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions