Gol*_*Man 5 python convention scope coding-style
我将PyCharm用于我的python程序,并且在下面编写了代码:
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
Run Code Online (Sandbox Code Playgroud)
因此,我收到一个警告文本,例如“外部作用域的阴影名称'ds'”。我知道范围的作用,但是我仍然想在范围的内部或外部使用相同的代码格式,例如“ for root,ds,fs in ....”。
我搜索过PEP8,但是,我仍然不知道如何在函数中规范地命名变量。
你能给我一些建议吗?
一般来说:忽略警告即可。这只是一个警告,而不是错误。您可以使用恰好匹配的全局名称和本地名称。
但是,无论如何我都不会os.walk()在全局范围内进行调用。我宁愿将其也放入一个函数中,它具有令人愉快的副作用,即您使用的名称不再是全局名称。
例如,您可以使用一个main()函数:
def main():
get_files_name()
for root, ds, fs in os.walk(other_dir):
pass
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
一般来说,您无论如何都不想root, ds, fs在模块中保留像全局变量这样的循环名称。这些是实现细节,不应成为模块公共 API 的一部分。如果必须for在全局范围内使用类似的循环,请_在名称上使用单下划线前缀,并考虑在循环后使用以下命令删除它们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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2191 次 |
| 最近记录: |