gpt4 book ai didi

python - 在将字符串与字节进行比较时,你能让 Python3 出错吗?

转载 作者:行者123 更新时间:2023-12-03 15:48:25 24 4
gpt4 key购买 nike

将代码从 Python 2 转换为 Python 3 时,一个问题是测试字符串和字节是否相等时的行为发生了变化。例如:

foo = b'foo'
if foo == 'foo':
print("They match!")

在 Python 3 上不打印任何内容,并且“它们匹配!”在 Python 2 上。在这种情况下很容易发现,但在许多情况下,检查是对可能已在其他地方定义的变量执行的,因此没有明显的类型信息。

我想让 Python 3 解释器在字符串和字节之间存在相等性测试时给出错误,而不是默默地得出它们不同的结论。有什么办法可以做到这一点吗?

最佳答案

( 已编辑 :修复我错误地建议修改实例上的 __eq__ 会影响 == 评估的问题,正如@user2357112supportsMonica 所建议的那样)。

通常,您可以通过覆盖 __eq__ 来做到这一点。您想要保护的类型的方法。
对您来说不幸的是,这不能用于内置类型,特别是 strbytes ,因此代码如下:

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!")

只会抛出:

AttributeError: 'bytes' object attribute '__eq__' is read-only


您可能需要使用以下内容手动保护比较:

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.")

用途如下:

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.


另一种选择是在您自己的 Python 分支中进行 hack 并覆盖 __eq__ .
请注意,Pypy 也不允许您覆盖内置类型的方法。

关于python - 在将字符串与字节进行比较时,你能让 Python3 出错吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62100772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com