python - pylint bad-format-string的解释

标签 python pylint

在以下文件中:

"""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/

相关文章:

python - pylint 重复代码误报

python - emacs:python 设置缩进选项卡(pylint、autopep8、flycheck 等问题)

Python 全局关键字与 Pylint W0603

python - 将两个不同的列合并为一列(说明是 name )

Python 请求,返回 : Unexpected character encountered while parsing value: L. 路径

linux - 如何在 vim 中使用 pylint

python - mypy vs mypy-lang vs pyls-mypy python包之间的区别

python - 几个模块的 Pytest init 设置

python - 为什么这个递归函数在满足其基本情况后仍然继续

python - 每个输入文件单独的测试用例?