0

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!
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 2
    `type()` returns the class not the name of the class: https://docs.python.org/3/library/functions.html#type – rdas Oct 18 '20 at 18:37
  • Beside the point, but the code in the traceback doesn't match the code you provided. – wjandrea Oct 18 '20 at 18:51

1 Answers1

1

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}))
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • oh it works perfectly ! thank you so much, but i don't still understand well why... i.e. type(line1) is shapely.geometry.linestring.LineString – ikemoto fumiko Oct 18 '20 at 19:29
  • 1
    @ikemoto Excellent! Which part are you confused about? BTW, don't forget to [upvote answers you find useful, and accept the best one](/help/someone-answers). – wjandrea Oct 18 '20 at 19:31
  • in jupyter notebook, when I execute just type(line1) then it produces shapely.geometry.linestring.LineString. so I expected in the def function, type() works the same... I hope you understand my point, but sorry I'm a python beginner! – ikemoto fumiko Oct 18 '20 at 19:38
  • @ikemoto I think you're confused because the name that you call a class doesn't have to be that class's full name. For example, I don't use Shapely, but if I do `from collections import Counter; Counter`, the output is `collections.Counter`, even though I'm referring to it by its basename. – wjandrea Oct 18 '20 at 19:50