Shailesh Tainwala
Shailesh Tainwala

Reputation: 6507

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

Think the title summarizes the question :-)

Upvotes: 59

Views: 40301

Answers (3)

Izana
Izana

Reputation: 3115

common: the code under __name__ == "__main__" guard will be executed.

differences:

  1. invoke path is different: sys.argv[0] and sys.path[0]

python -m will use the search path (PYTHONPATH), and you can execute the code anywhere.

python script.py will assume using the same location with the script as the sys.path[0] (first search path), and relative imports may fail (e.g., if dependent module is in parent dir, and parent dir is not in search path). Whereas python -m will use the root of the python lib as the sys.path[0]

  1. module is meant to be reused. script is usually one-off thing.

example code:

import sys

def main():
    print("path", sys.path)
    print("argv", sys.argv[0])


if __name__ == "__main__":
    main()

and have a dir structure:

$ tree tmp
tmp
├── __init__.py
└── hello.py

and try it yourself.

Upvotes: 2

Andrew Aylett
Andrew Aylett

Reputation: 40710

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.

Upvotes: 64

Duncan
Duncan

Reputation: 95652

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.

Upvotes: 32

Related Questions