Reputation: 459
I have a class that needs to have variable that is list and contains points, those represents vertices in shape.
I'm writing a point in that way: a = [x, y]
so the list of points will be list(list)?
this is my vertices setter:
def set_vertices(self, vertices):
if not isinstance(vertices, list(list)):
raise TypeError("vertices must be list of points")
self.__vertices = vertices
but pycharm tells me that list(list) should be replaced by: "Union[type, tuple]"
and this code:
f = Figure(self.position);
f.set_vertices([[2, 2], [2, 2], [2, 2], [2, -2]])
raises an exception: TypeError: 'type' object is not iterable
Upvotes: 3
Views: 541
Reputation: 236114
That's because list(list)
is not a valid type in Python, we have to find a different way to check if vertices
belongs to the required type - namely, a list of lists. How about this?
if not isinstance(vertices, list) or not all(isinstance(v, list) for v in vertices):
raise TypeError("vertices must be list of points")
Also, consider if an empty list is a valid input for your use case, and whether you want to check if each point has exactly two integer coordinates.
But above all, think carefully about why do you want to check the input type like that. Python is a dynamically typed language, it doesn't make much sense to manually check if the input conforms to an expected type as in other languages; if the input type is wrong in any way it'll raise an error at runtime and that's fine - it's easier to ask for forgiveness than permission, and that applies to type checking, too.
Upvotes: 1