Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
Last active December 29, 2015 10:19
Show Gist options
  • Save davidallsopp/7656236 to your computer and use it in GitHub Desktop.
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…
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