pythonbuck

If a logging warning occurs before __main__, how is it being called?


I'm working on a corporate python program which uses buck build. When I run part of the program, abc.py (via a .par file), then it runs the program starting with if __name__ == "__main__" etc.

However, I'm trying to find source of logging warnings that occur before any of the contents of the if __name__ ... are run. Or perhaps keywords to understand this better. What could be running before the main file?


Solution

  • Your mistake is thinking execution starts with if __name__ == "__main__":. That check is a guard that prevents the guarded code from executing when imported as a module, rather than run as the main script. The unguarded code always runs, regardless of how the module is loaded, so if the guard is at the bottom of the file, the rest of the file is run before it is reached.

    So if you have a module:

    # foo.py
    print("foo")
    

    And a script:

    # main.py
    import foo
    
    def main():
        print("Main")
    
    if __name__ == '__main__':
        main()
    

    and you run python3 main.py, execution of main.py begins with import foo, which ends up printing foo immediately. Then main.py defines the main function (defining functions without calling them is still executing code; if Python had skipped to the guarded code, main wouldn't exist), then the guard is checked, the check passes, and main is called. Basically every bit of top-level code (typically imports, global constants, functions, and class definitions) is executed before the guarded block is reached; normally that top-level code does nothing visible, but if an imported module tried to do some real work and logged during the process, it would take effect before you ever reached your guarded "main script" code.