28

How can I check if a polygon entity is actually a multipolygon? I've tried:

if len(polygon) > 1:

but then get the error:

TypeError: object of type 'Polygon' has no len()

I've tried Nill, None and others, nothing worked.

Georgy
  • 12,464
  • 7
  • 65
  • 73
Yair
  • 859
  • 2
  • 12
  • 27
  • You should check the manual. You can read about `class MultiPolygon` here: http://toblerity.org/shapely/manual.html#collections-of-polygons – Alessandro Trinca Tornidor Aug 25 '16 at 10:37
  • This works only if your variable is a multipolygon. If it is not - you`ll get that error. This is why I want to check whether my variable is a polygon or a multipolygon. – Yair Aug 25 '16 at 10:46

3 Answers3

52

Use the object.geom_type string (see general attributes and methods).

For example:

if poly.geom_type == 'MultiPolygon':
    # do multipolygon things.
elif poly.geom_type == 'Polygon':
    # do polygon things.
else:
    # raise IOError('Shape is not a polygon.')
Rick
  • 347
  • 4
  • 16
jmsinusa
  • 1,584
  • 1
  • 13
  • 21
7

Ok, this worked for me:

print ('type = ', type(poly))

outputs with:

type =  <class 'shapely.geometry.polygon.Polygon'>

in case of a polygon, and:

type =  <class 'shapely.geometry.multipolygon.MultiPolygon'>

in case of a multipolygon.

To check if a variable is a polygon or a multypolygon I did this:

if (isinstance(poly, shapely.geometry.multipolygon.MultiPolygon)):
    code...
Yair
  • 859
  • 2
  • 12
  • 27
  • Worth noting that this will not tell you how many rings the multipolygon has. A multipolygon may have only one exterior ring. That may not matter for your use case. – jpmc26 Oct 21 '16 at 23:03
  • Using your `isinstance()` code, I get: `NameError: name 'shapely' is not defined` – jane Nov 01 '19 at 00:32
  • 1
    @jane that means you have not imported shapely (or not as shapely). Add `import shapely` to the top of your code – Fee Mar 26 '21 at 11:17
0

you can do this simply.

import shapely.geometry.multipolygon as sh

if isinstance(polygon, sh.MultiPolygon):
    print('yes I am')
Tim
  • 513
  • 5
  • 20