Python Forum
module detecting if imported vs not - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: module detecting if imported vs not (/thread-35580.html)



module detecting if imported vs not - Skaperen - Nov-19-2021

how can a module detect if it is being imported, possibly by a command script, as opposed to being run directly?


RE: module detecting if imported vs not - Yoriz - Nov-19-2021

https://docs.python.org/3/library/__main__.html Wrote:a module can discover whether or not it is running in the top-level environment by checking its own __name__, which allows a common idiom for conditionally executing code when the module is not initialized from an import statement:

if __name__ == '__main__':
    # Execute when the module is not initialized from an import statement.
    ...
...