Last active
December 29, 2015 10:19
-
-
Save davidallsopp/7656236 to your computer and use it in GitHub Desktop.
A slightly typesafe (!) comparison function in Python. Only a runtime check of course, but will fail fast with a clear exception rather than silently comparing different types than can never be equal. I'm sure this is wildly unpythonic, but given that I've seen bugs from this kind of comparison even in statically typed languages like Java and Sc…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def eq(first, *rest): | |
for r in rest: | |
assert type(first) is type(r), "Different types %s, %s for inputs (%s,%s)" % (type(first), type(r), first, r) | |
if first != r: | |
return False | |
return True | |
# eq(1) - True | |
# eq(1, 1) - True | |
# eq(1, 1, 1) - True | |
# eq(1, 1, 2) - False | |
# eq(1, '1') - AssertionError | |
# eq(1, 1, '1') - AssertionError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment