Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/06-Modules and Packages/01-Name_and_Main/Explanation.txt
Views: 648
Sometimes when you are importing from a module, you would like to know whether1a modules function is being used as an import, or if you are using the original2.py file of that module. In this case we can use the:34if __name__ == "__main__":56line to determine this. For example:78When your script is run by passing it as a command to the Python interpreter:910python myscript.py1112all of the code that is at indentation level 0 gets executed. Functions and13classes that are defined are, well, defined, but none of their code gets ran.14Unlike other languages, there's no main() function that gets run automatically15- the main() function is implicitly all the code at the top level.1617In this case, the top-level code is an if block. __name__ is a built-in variable18which evaluate to the name of the current module. However, if a module is being19run directly (as in myscript.py above), then __name__ instead is set to the20string "__main__". Thus, you can test whether your script is being run directly21or being imported by something else by testing2223if __name__ == "__main__":24...2526If that code is being imported into another module, the various function and27class definitions will be imported, but the main() code won't get run. As a28basic example, consider the following two scripts:2930# file one.py31def func():32print("func() in one.py")3334print("top-level in one.py")3536if __name__ == "__main__":37print("one.py is being run directly")38else:39print("one.py is being imported into another module")4041and then:4243# file two.py44import one4546print("top-level in two.py")47one.func()4849if __name__ == "__main__":50print("two.py is being run directly")51else:52print("two.py is being imported into another module")5354Now, if you invoke the interpreter as5556python one.py5758The output will be5960top-level in one.py6162one.py is being run directly63If you run two.py instead:6465python two.py6667You get6869top-level in one.py70one.py is being imported into another module71top-level in two.py72func() in one.py73two.py is being run directly7475Thus, when module one gets loaded, its __name__ equals "one" instead of __main__.767778