What is the difference between a module and a script in Python?

Question:

Think the title summarizes the question 🙂

Asked By: Shailesh Tainwala

||

Answers:

A script is generally a directly executable piece of code, run by itself. A module is generally a library, imported by other pieces of code.

Note that there’s no internal distinction — both are executable and importable, although library code often won’t do anything (or will just run its unit tests) when executed directly and importing code designed to be a script will cause it to execute, hence the common if __name__ == "__main__" test.

Answered By: Andrew Aylett

Any Python module may be executed as a script. The only significant difference is that when imported as a module the filename is used as the basis for the module name whereas if you execute it as a script the module is named __main__.

This distinction makes it possible to have different behaviour when imported by enclosing script specific code in a block guarded by if __name__=="__main__". This has been known to cause confusion when a user attempts to import the main module under its own name rather than importing __main__.

A minor difference between scripts and modules is that when you import a module the system will attempt to use an existing .pyc file (provided it exists and is up to date and for that version of Python) and if it has to compile from a .py file it will attempt to save a .pyc file. When you run a .py file as script it does not attempt to load a previously compiled module, nor will it attempt to save the compiled code. For this reason it may be worth keeping scripts small to minimise startup time.

Answered By: Duncan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.