Python equal operator, avoid bugs of type: (<string> == <number>) -> False
-
06-07-2021 - |
문제
Is there a way to obtain an exception when the == (equal) operator is used to compare different types? Python 3 throws an exception when attempting to order objects of different types. But == still returns False.
Or is there some other way to avoid hard to detect bugs caused by wrong type assumptions? Are there any design-patterns that could help?
I'm thinking of, e.g., a case where someone uses someone elses implementation of xmlparser.get() which always returns a string, even if the property is basically a number.
해결책
No. Because for ==, the reasoning is that equality implies comparibility. If two objects aren't even comparable they are not equal, therefore it will return false and never throw an exception.
다른 팁
No, python is inherently dynamically typed.
If you must doublecheck a type, use the isinstance()
function, or use duck typing to test for specific behaviour.
I'm thinking of, e.g., a case where someone uses someone elses implementation of xmlparser.get() which always returns a string, even if the property is basically a number.
You might want to coerce the value to a number by calling int
or float
on it, as appropriate.
Despite the fact that Python has dynamic typing, it is strong (not duck). So:
>>> 42 == 42
True
>>> 42 == 42.0
True
>>> 42 == "42"
False
>>> 42 == int("42")
True
You have to perform an explicit type conversion when getting a string representation of the number.
On the other hand, you can manage comparison of your custom objects by defining methods __eq__(self, other)
or __cmp__(self, other)
in your class.