Search code examples
pythonif-statementstandards

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


It appears as if variables can be located both inside and outside the if __name__ == "__main__": block. In this case I place a file path variable within the if block. However, the code works if I place the path variable outside the if block too.

def do_something(path):
    print(path)

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

Are there any Python standards that dictate whether or not variables such as path should be placed inside or outside the if __name__ == "__main__": block?


Solution

  • Python is happy with either approach, but if you want to write libraries and command-line programs that are importable, testable, and flexible for future evolution, my general advice is to put all substantive code (other than imports and constants) inside of functions or methods. There are occasionally strong reasons to deviate from that pattern, but my default approach looks like this tiny example:

    # 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()