如何正确命名变量以避免像 Python 中的 "Shadows name from outer scope" 这样的警告

How to name variable correctly to avoid warning like "Shadows name from outer scope" in Python

我的python程序使用PyCharm,我写了下面的代码:

def get_files_name():
    root_dir = "/Volumes/NO NAME/"
    for root, ds, fs in os.walk(root_dir):
        for f in fs:
            print(os.path.join(root_dir, f))


get_files_name()
for root, ds, fs in os.walk(other_dir):
    pass

所以我收到了类似 "Shadows name 'ds' from outer scope" 的警告文本。 我知道作用域的影响,但我仍然想在作用域内部或外部使用 "for root, ds, fs in ...." 等相同的代码格式。

PEP8我都搜过了,但是还是不知道函数中的变量如何规范命名。

你能给我一些建议吗?

总的来说:忽略警告即可。这只是一个警告,而不是错误。您同时使用了恰好匹配的全局名称和本地名称。

但是,无论如何我都不会在全局范围内调用 os.walk() 。我宁愿把它也放到一个函数中,它有快乐的 side-effect 你使用的名称不再是全局变量。

例如,您可以使用 main() 函数:

def main():
    get_files_name()
    for root, ds, fs in os.walk(other_dir):
        pass

if __name__ == '__main__':
    main()

一般来说,您无论如何都不想在模块中留下像 root, ds, fs 这样的循环名称作为全局变量。这些是实现细节,不应成为模块 public API 的一部分。如果您在全局范围内使用像这样的for循环,请在名称上使用_ single-underscore前缀并考虑在循环 del:

for _root, _ds, _fs in os.walk(other_dir):
    # do something with the files or directories

# clean variables for the loop that are not part of the API
del _root, _ds, _fs

警告 shadows name XX from outer scope 不是 PEP8 问题,而是来自 Pycharm 的实际警告,告诉您以这种方式重用变量名是个坏主意。换句话说,这不是代码风格问题,而是以后在更大的程序中可能会带来问题。

我的建议是,嗯,尽可能避免重复使用变量名。输入:

for root_path, directory_name, file_name in os.walk(root_dir):

不会花费很多时间,并且会在将来避免不受欢迎的side-effects。

不过,如果出于任何原因您绝对需要重用变量名并希望摆脱警告消息,您可以在 Pycharm 中禁用它(首选项 -> 编辑器 -> 代码样式 -> 检查-> 从外部范围隐藏名称)。但这通常是个坏主意。

如果您的名字重复,请使用“_”来避免这种warnings.It的常见做法。

def get_files_name():
    root_dir = "/Volumes/NO NAME/"
    for root, _ds, fs in os.walk(root_dir):
        for f in fs:
            print(os.path.join(root_dir, f))

get_files_name()
for root, _ds, fs in os.walk(other_dir):
    pass