变量应该位于 if __name__ == "__main__": 块的内部还是外部?

Should variables be located inside or outside of if __name__ == "__main__": block?

看起来好像变量可以位于 if __name__ == "__main__": 块的内部和外部。在本例中,我在 if 块中放置了一个文件路径变量。但是,如果我也将 path 变量放在 if 块之外,代码就可以工作。

def do_something(path):
    print(path)

if __name__ == "__main__":
    path = '/path/to/my/image.tif'
    do_something(path)

是否有任何 Python 标准规定 path 等变量应该放在 if __name__ == "__main__": 块的内部还是外部?

视情况而定。如果程序的路径是不变的,那么它可以在 if 块之外。但是,如果它只是一个输入(而不是程序的一部分),它应该在 if 块内

Python 对这两种方法都很满意,但是如果你想编写库和 可导入、可测试且对未来灵活的命令行程序 进化,我的一般建议是将所有实质性代码(导入除外 和常量)在函数或方法中。偶尔有强 偏离该模式的原因,但我的默认方法如下所示 小例子:

# Imports.

import sys

# Constants.

DEFAULT_PATH = '/path/to/my/image.tif'

# The library's entry point.

def main(args = None):
    args = sys.argv[1:] if args is None else args
    path = args[0] if args else DEFAULT_PATH
    helper(path)

# Other functions or classes needed by the program.

def helper(path):
    print(path)

# The program's command-line entry point.

if __name__ == '__main__':
    main()