在以下文件中:
"""hello I am the module spam.py"""
from __future__ import unicode_literals
'hello {world}'.format(world='potato')
我们有以下 bad-format-string
的 pylint 违规:
wim@SDFA100461C:/tmp$ pylint --reports=n spam.py
No config file found, using default configuration
************* Module spam
W: 3, 0: Invalid format string (bad-format-string)
我不明白这个建议,pylint 开发者说检查是关于 PEP 3101风格,但我在 PEP 中没有看到任何违反此处的内容。
问题是什么? pylint 希望我们对此做什么?
下面是版本号。
wim@SDFA100461C:/tmp$ pylint --version
No config file found, using default configuration
pylint 1.3.0,
astroid 1.2.0, common 0.62.1
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2]
最佳答案
这是 pylint
中的错误;它假定所有字符串格式都是字节字符串。
linter 解析格式,然后解析占位符名称。因为您使用的是 Unicode 文字,所以这会产生一个 unicode
name 也是,但解析器假设它只会遇到字节串;如果没有,它假设它找到了一个整数:
if not isinstance(keyname, str):
# In Python 2 it will return long which will lead
# to different output between 2 and 3
keyname = int(keyname)
这引发了一个 ValueError
您的格式字符串为 world
被解析为 unicode
取而代之的值(value):
>>> import string
>>> formatter = string.Formatter()
>>> parseiterator = formatter.parse(u'hello {world}')
>>> result = next(parseiterator)
>>> result
(u'hello ', u'world', u'', None)
>>> keyname, fielditerator = result[1]._formatter_field_name_split()
>>> keyname
u'world'
ValueError
异常然后又被捕获并转换为 IncompleteFormatString
异常,然后导致 W1302
错误代码。
参见 parse_format_method_string
function .
应该更改那里的测试以测试与 format_string
相同的类型相反:
if not isinstance(keyname, type(format_string)):
# In Python 2 it will return long which will lead
# to different output between 2 and 3
keyname = int(keyname)
这将在 Python 2 和 3 中做正确的事情。
关于python - pylint bad-format-string的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25057443/