58

我制作了一个简单的 python 脚本来在网站上发布数据。

#Imports

url_to_short = sys.argv[1]

post_url = 'https://www.googleapis.com/urlshortener/v1/url'
headers = {'Content-Type': 'application/json'}

data = {'longUrl': url_to_short}
post_data = json.dumps(data)

req = urllib2.Request(post_url, post_data, headers)
resp = urllib2.urlopen(req)

if resp.getcode() == 200:  
    content = json.loads(resp.read())

#Other stuff

现在我想让我们用pylint工具检查我的脚本的编码标准。

我的pylint输出如下:

************* Module post
C:  1,0: Missing docstring
C:  6,0: Invalid name "url_to_short" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C:  8,0: Invalid name "post_url" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C:  9,0: Invalid name "headers" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)

# Other stuff

现在,我的问题是为什么pylint将我的变量名显示为Invalid name. 以这种方式命名变量是错误的编码约定。

完整的 pylint 输出

4

3 回答 3

60

由于您的代码不包含在类或函数中,因此期望这些变量是常量,因此它们应该是大写的。

您可以阅读PEP8以获取更多信息。

于 2012-05-30T11:45:30.557 回答
27

编辑:正如其他人所提到的,pylint 期望全局变量应该是大写的。如果警告真的困扰你,你可以通过将这样的小片段包装main()在 -function 中然后使用if __name__ == "__main__"-convention 来规避它们。或者,如果您关心,您可以修改 pylint 用于验证变量名称的正则表达式。

来自 Pylint 的开发人员

在这种情况下,Pylint 告诉我这些变量似乎是常量,应该全部大写。该规则实际上是 Logilab 中创建 Pylint 的人员所特有的命名约定。这就是他们选择命名这些变量的方式。您也可以创建自己的内部命名约定,但出于本教程的目的,我们希望坚持 PEP-8 标准。在这种情况下,我声明的变量应该遵循所有小写的约定。适当的规则类似于:“应该匹配 [a-z_][a-z0-9_]{2,30}$”。注意正则表达式中的小写字母(az 与 AZ)

您可以通过运行来测试它: pylint --const-rgx='[a-z_][a-z0-9_]{2,30}$' x.py

于 2012-05-30T11:47:17.997 回答
7

这是因为url_to_short是在全局命名空间中声明的,而 pylint 需要将全局变量(例如常量)命名为ALL_UPPERCASE.
因此,它会检查您的变量名称是否与用于全局变量的正则表达式匹配,即:((([A-Z_][A-Z0-9_]*)|(__.*__))$注意A-Z范围)。因此Invalid name错误。

于 2012-05-30T11:46:51.027 回答