(EDITED: to fix an issue where I was incorrectly suggesting that modifying __eq__
on the instance would affect the ==
evaluation as suggested by @user2357112supportsMonica).
Normally, you would do this by overriding the __eq__
method of the type(s) you would like to guard.
Unfortunately for you, this cannot be done for built-in types, notably str
and bytes
, therefore code like this:
foo = b'foo'
bytes.__eq__ = ... # a custom equal function
# str.__eq__ = ... # if it were 'foo' == foo (or `type(foo)`)
if foo == 'foo':
print("They match!")
would just throw:
AttributeError: 'bytes' object attribute '__eq__' is read-only
You may need to manually guard the comparison with something like:
def str_eq_bytes(x, y):
if isinstance(x, str) and isinstance(y, bytes):
raise TypeError("Comparison between `str` and `bytes` detected.")
elif isinstance(x, bytes) and isinstance(y, str):
raise TypeError("Comparison between `bytes` and `str` detected.")
to be used as follows:
foo = 'foo'
if str_eq_bytes(foo, 'foo') or foo == 'foo':
print("They match!")
# They match!
foo = 'bar'
if str_eq_bytes(foo, 'foo') or foo == 'foo':
print("They match!")
# <nothing gets printed>
foo = b'foo'
if str_eq_bytes(foo, 'foo') or foo == 'foo':
print("They match!")
TypeError: Comparison between `bytes` and `str` detected.
The other option would be to hack in your own Python fork and override __eq__
.
Note that also Pypy does not allow you to override methods for built-in types.
1 == "one"
also just givesFalse
, while1 == 1.0
givesTrue
. Python doesn't consider comparing values of different types an error and the semantics of it depend on the types involved. – Nicolette