为什么 __rmod__ 不能对字符串正常工作? [英] Why doesn't __rmod__ work properly for strings?

查看:45
本文介绍了为什么 __rmod__ 不能对字符串正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<预><代码>>>>类 MyInt(int):... def __rmod__(self, other):...返回 42...>>>类 MyStr(str):... def __rmod__(self, other):...返回'wat'...>>>0 % 我的 ()42>>>'%r' % MyStr()''"

为什么int子类可以从反射端控制这个BinOp,而str不能?这似乎与记录在案的 datamodel 相矛盾.

我希望使用该功能来创建一个非侵入性和向后兼容的扩展,为 logging 框架提供花括号样式的处理程序/格式化程序,但这让我停下了脚步.这是一个错误吗?

Linux 上的 Python 3.6.0.使用 collections.UserString 作为基类也有问题.使用 bytes 作为基础不会.

解决方案

这是 Python 问题 28598.快速路径 % 字节码评估循环中的字符串格式不检查字符串子类.它现已修复,所以更新你的 Python 到 v3.6.1+.

>>> class MyInt(int):
...     def __rmod__(self, other):
...         return 42
...     
>>> class MyStr(str):
...     def __rmod__(self, other):
...         return 'wat'
...     
>>> 0 % MyInt()
42
>>> '%r' % MyStr()
"''"

Why is the int subclass able to control this BinOp from the reflected side, but str can not? This seems to contradict the documented datamodel.

I was hoping to use the feature to create a non-intrusive and backwards-compatible extension providing curly-braces-style handlers/formatters for the logging framework, but this stopped me in my tracks. Is that a bug?

Python 3.6.0 on Linux. Using collections.UserString as a base class also has the issue. Using bytes as a base does not.

解决方案

This is Python issue 28598. The fast path for % string formatting in the bytecode evaluation loop wasn't checking for string subclasses. It's fixed now, so update your Python to v3.6.1+.

这篇关于为什么 __rmod__ 不能对字符串正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆