pythonshapely

Subclassing Polygon in Shapely


I'm working with Shapely in Python and trying to subclass the Polygon class. However, I'm encountering an error when trying to add a custom attribute during object creation. Could you please provide guidance on how to subclass the Polygon class in Shapely and add custom attributes without running into this error?

This is what I tried so far:

from shapely.geometry import Polygon


class CustomPolygon(Polygon):

    def __init__(self, shell=None, holes=None, name=None):
        super().__init__(shell, holes)
        self._name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value


polygon1 = CustomPolygon([(0, 0), (0, 1), (1, 1), (1, 0)], name="Polygon1")

And this is the error I get:

polygon1 = CustomPolygon([(0, 0), (0, 1), (1, 1), (1, 0)], name="Polygon1")
TypeError: __new__() got an unexpected keyword argument 'name'

Solution

  • You need to downgrade shapely to version 1.7 unfortunately. They intentionally got rid of any subclassing capability in 1.8 and they explicitly say they aren't going to support it anymore. See the issue here:

    https://github.com/shapely/shapely/issues/1698