Search code examples
pythonpython-3.xshapely

TypeError: cannot unpack non-iterable MultiPoint object


In my python app I am using Shapely. Invoking the function below:

def get_t_start(t_line: geometry.LineString):
    print('get_t_start', t_line.boundary)
    p1, p2 = t_line.boundary
    t_start = p1 if p1.y < p2.y else p2
    return t_start

produces the following output:

get_t_start MULTIPOINT (965 80, 1565 1074) Traceback (most recent call last):
... File "/sites/mpapp.py", line 13, in get_t_start p1, p2 = t_line.boundary
TypeError: cannot unpack non-iterable MultiPoint object

From the print of t_line.boundary I guess the object is ok. I am sure I have used this object (MULTIPOINT) like this in other apps to get the boundary points. I really can't figure out why now this is not working.


Solution

  • That's most likely because your apps are running different versions of shapely. Starting with Shapely 1.8, iteration over multi-part geometries (like a MultiPoint) is deprecated and was removed in Shapely 2.0 (read more).

    So, you just need to access the boundary's geoms :

    from shapely import LineString, Point
    
    def get_t_start(t_line: LineString) -> Point:
        print("get_t_start", t_line.boundary)
        p1, p2 = t_line.boundary.geoms           # << here
        t_start = p1 if p1.y < p2.y else p2
        return t_start
    

    Output :

    from shapely import from_wkt
    
    line = from_wkt("LINESTRING (965 80, 1565 1074)")
    
    >>> get_t_start(line)
    
    # get_t_start MULTIPOINT (965 80, 1565 1074)
    
    # + a display of the point