Search code examples
pythonassert

How to resolve AssertionError on checking type() by assert?


I am trying to check if the object I input in the code is a Shapely Point, LineString or Polygon geometry with the assert function. My code always produces this 'AssertionError' I put below the code, and I couldn't understand why or solve it...

def get_centroid(geom):
    assert type(geom) == 'shapely.geometry.point.Point' or type(geom) == 'shapely.geometry.linestring.LineString' or type(geom) == 'shapely.geometry.polygon.Polygon', "Input should be a Shapely geometry!"
    return print(geom.centroid)

points1 = [Point(45.2,22.34),Point(100.22,-3.20)]
line1 = create_line_geom(points1)

get_centroid(line1)
AssertionError                            Traceback (most recent call last)
<ipython-input-33-6cb90e627647> in <module>
----> 1 get_centroid(line1)

<ipython-input-30-9f649b37e9c2> in get_centroid(geom)
      1 # YOUR CODE HERE
      2 def get_centroid(geom):
----> 3     assert type(geom) == 'shapely.geometry.linestring.LineString', "Input should be a Shapely geometry!"
      4     return print(geom.centroid)

AssertionError: Input should be a Shapely geometry!

Solution

  • type() returns the class itself, not the class's name. So you should use something more like type(geom) == Point. However, you can do multiple "or equals" more easily by using in to check set membership:

    type(geom) in {Point, LineString, Polygon}
    

    Note that this excludes subclasses. To include them, use isinstance():

    any(isinstance(geom, t) for t in {Point, LineString, Polygon}))