开发者

What's the point of a main function and/or __name__ == "__main__" check in Python? [duplicate]

开发者 https://www.devze.com 2022-12-15 04:57 出处:网络
This question already has answers here: What does if __name__ == "__main__": do? (43 answers)
This question already has answers here: What does if __name__ == "__main__": do? (43 answers) Closed 4 months ago.

I occasionally notice something like the following in Python scripts:

if __name__ ==开发者_高级运维 "__main__":
    # do stuff like call main()

What's the point of this?


Having all substantial Python code live inside a function (i.e., not at module top level) is a crucial performance optimization as well as an important factor in good organization of code (the Python compiler can optimize access to local variables in a function much better than it can optimize "local" variables which are actually a module's globals, since the semantics of the latter are more demanding).

Making the call to the function conditional on the current module being run as the "main script" (rather than imported from another module) makes for potential reusability of nuggets of functionality contained in the module (since other modules may import it and just call the appropriate functions or classes), and even more importantly it supports solid unit testing (where all sort of mock-ups and fakes for external subsystems may generally need to be set up before the module's functionality is exercised and tested).


This allows a python script to be imported or run standalone is a sane way.

If you run a python file directly, the __name__ variable will contain __main__. If you import the script that will not be the case. Normally, if you import the script you want to call functions or reference classes from the file.

If you did not have this check, any code that was not in a class or function would run when you import.


The sole purpose of this, assuming it is in main.py, is so other files can import main to include classes and functions that are in your "main" program, but without running the source code.

Without this condition, code that is in the global scope will be executed when it is imported by other scripts.


It's a great place to put module tests. This will only run when a module is run directly from the shell but it will not run if imported.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号