gpt4 book ai didi

python - 为什么pylint在函数外部需要大写变量名?

转载 作者:太空宇宙 更新时间:2023-11-03 13:57:05 25 4
gpt4 key购买 nike

为什么 pylint 在函数外部接受大写变量而在函数内部拒绝它们?相反,为什么 pylint 拒绝函数外的 camelCase 并在函数内部接受它?

我刚刚安装了 pylint(版本 2.2.2)来检查我的 Python 3。一定有什么我错过了。我的相关 Python/包版本是:

pylint 2.2.2
astroid 2.1.0
Python 3.6.7 | packaged by conda-forge | (default, Nov 20 2018, 18:20:05)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)]

考虑以下代码 (test_1),我在其中使用驼峰式命名和大写变量命名。 Capitalized 变量被接受(为什么?)并且 camelCase 被拒绝(因为代码没有包装到函数中,我猜)。

'''
Nothing important
'''

fileHandler = open("afile.txt")

for line in fileHandler:
Token = line.split("\t")
Part_1 = Token[0]
print(Part_1)

在调用 pylint 时给出:

$ pylint --py3k --enable=all  test_1.py 
************* Module test_1
test_1.py:5:0: C0103: Constant name "fileHandler" doesn't conform to UPPER_CASE naming style (invalid-name)

------------------------------------------------------------------
Your code has been rated at 8.00/10 (previous run: 8.00/10, +0.00)

现在,如果我将所有内容都放入一个函数 (test_2) 中。

'''
Nothing important
'''

def foo():
fileHandler = open("afile.txt")

for line in fileHandler:
Token = line.split("\t")
Part_1 = Token[0]
print(Part_1)

if __name__ == '__main__':
foo()

然后大写变量被检测为不合规(这是我所期望的):

$ pylint --py3k --enable=all  test_2.py
************* Module test_2
test_2.py:5:0: C0102: Black listed name "foo" (blacklisted-name)
test_2.py:5:0: C0111: Missing function docstring (missing-docstring)
test_2.py:6:4: C0103: Variable name "fileHandler" doesn't conform to snake_case naming style (invalid-name)
test_2.py:9:8: C0103: Variable name "Token" doesn't conform to snake_case naming style (invalid-name)
test_2.py:10:8: C0103: Variable name "Part_1" doesn't conform to snake_case naming style (invalid-name)

------------------------------------------------------------------
Your code has been rated at 3.75/10 (previous run: 3.75/10, +0.00)

我有些不清楚...欢迎任何澄清...

最佳

最佳答案

当您将变量放入函数内时,pylint 不再将它们“视为”常量。将变量放入函数后,pylint 将它们“视为”普通变量,不再需要您将它们大写,而是需要“snake_case”。请注意,默认情况下,pylint 更喜欢 snake_case 而不是 camelCase,但您可以 override this.pylintrc 中更喜欢 camelCase。

Python 脚本(无方法)

#!/usr/bin/env python3

# pylint wants 'FILEHANDLER'
fileHandler = open("afile.txt") # <-- pylint sees constant, wants UPPER_CASE

for line in fileHandler:
Token = line.split("\t")
Part_1 = Token[0]
print(Part_1)

用一个方法

#!/usr/bin/env python3

def run_stuff():

# pylint wants 'file_handler'
fileHandler = open("afile.txt") # <-- pylint sees normal variable

for line in fileHandler:
Token = line.split("\t")
Part_1 = Token[0]
print(Part_1)

if __name__ == '__main__':
run_stuff()

通常,.pylintrc 文件会跟在PEP8 之后.如果未提供,它将默认为 PEP8,如 pylint website 中所述.快乐 linting!

关于python - 为什么pylint在函数外部需要大写变量名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54151197/

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