Jov*_*vik 17 python global global-variables pylint
Pylint W0603说:
使用全局声明.在使用"global"语句更新全局变量时使用.PyLint只是试图阻止这种用法.这并不意味着你不能使用它!
我想知道为什么会这样?是否有更多Pythonic方法在函数内修改不可变的模块范围变量?是否建议将它们打包在像字典这样的可变变量中?或者可能将整个模块变成课堂?
在我看来,当变量被建议为"私有"(以_或__为前缀)时,此警告应该消失.
gur*_*lex 26
全局变量的广泛使用会使维护变成一场噩梦,因为它们会跟踪程序的流程,有时候会出现奇怪的错误,因为某些模块已经读取变量并在其他模块更改变量值之前对其值起作用(这可能是因为在某些不相关的第3个模块中反转了两个import语句).另请参阅全局变量的维基百科条目.
这就是为什么你应该避免可变的全局变量,IMO以及Pylint发出警告的原因(并且可能应该发出更多的警告.检测global关键字的使用只是发现其中一些的简单方法).
不要误解我:我不是说你不能使用全局变量.只有你应该避免使用它们.Python中有很多关于全局变量的合法案例.只要你没有超过几个W0603,你应该好.
现在,Logilab(维护Pylint的公司,以及我以前工作的地方)曾经不得不接管维护一块> 50kloc的Python代码,包含大量重复和100多个可变全局变量.这真是地狱.
解决全局变量的解决方案包括:
我会替换这个:
the_file = None
def open_the_file(fname):
global the_file
the_file = open(fname)
def write_to_the_file(data):
the_file.write(data)
open_the_file("boo")
write_to_the_file("Hi!")
Run Code Online (Sandbox Code Playgroud)
有了这个:
class FileProgram(object):
def __init__(self):
self.the_file = None
def open_the_file(fname):
self.the_file = open(fname)
def write_to_the_file(data):
self.the_file.write(data)
if __name__ == "__main__":
prog = FileProgram()
prog.open_the_file("boo")
prog.write_to_the_file("Hi!")
Run Code Online (Sandbox Code Playgroud)
你可能会说,"这对我的简单任务来说太复杂了!" 好的,那就不要在你的程序上运行pylint了.你不能要求pylint明白你的程序太小而不能使用好的结构.
| 归档时间: |
|
| 查看次数: |
15122 次 |
| 最近记录: |