Skip to content
Fullstack Launchpad

Python Modules and Packaging #5.2

How you run a module determines its name. The project environment determines which libraries are available to import.

By Published Updated 4 min readPython for Engineers Switching Languages

Two ways to run the same file

What does this code print? Save it as cli.py and run the file with Python. Each module has a name in __name__. Its value depends on how you run the file.

python
print(__name__)
# prints: __main__

Start Python in the same directory and type import cli. That same line now prints cli. Two details explain the difference: where Python finds a module and what it does once it finds it.

SectionExampleResult
Find a module in a packageimport html.parserLoads the submodule html.parser
Run a modulepython -m orbit.cliPrints Orbit with the file below
Choose an environmentpython -m venv .venvCreates an environment in .venv

How some other languages compare

LanguageDeclare dependenciesPin versionsWhere libraries live
Python (uv)pyproject.tomluv.locka .venv per project
Node.jspackage.jsonpackage-lock.jsonnode_modules
Java (Maven)pom.xmlnone by defaultshared ~/.m2
Gogo.modgo.sumshared module cache

Where does Python find a module?

A .py file can be a module. A package groups modules under a common name. For example, the standard library has an html package with a parser module inside.

SyntaxMeaning
import html.parserLoad the submodule and bind the name html in the current scope
html.parserAccess the submodule through the package
python
import html.parser
import sys

print(html.parser.__name__)
# prints: html.parser
print(sys.modules["html.parser"] is html.parser)
# prints: True

Python first checks sys.modules, which holds modules already loaded. If a package on disk such as html is missing from the cache, Python looks for that top-level name in each directory in sys.path, in order. It then looks for parser on the package's own search path. Python runs a regular package's __init__.py the first time it loads the package. The file can be empty.

When does main run?

Create an orbit directory with two files: an empty __init__.py and a cli.py containing the code below. Put the startup call behind a check on the module name. A test file can then import the function without starting the program.

SyntaxMeaning
__name__ == "__main__"True when Python runs this module as the main program
main()Call the function defined here. Naming it main doesn't invoke it
python
def main():
    print("Orbit")


if __name__ == "__main__":
    main()
    # prints: Orbit

Run each command from the parent directory of orbit, in a fresh process.

text
python -c "import orbit.cli"
python -m orbit.cli

The first command executes the statement after -c. Python names the module orbit.cli, so it defines the function and prints nothing. The second command uses -m to find the module by name and run it as __main__. The condition is now true and the function prints Orbit.

Project environments and dependencies

A virtual environment (venv) has its own directory for installed libraries. Create one with the standard library, then ask its interpreter which environment it's using. These paths work on macOS and Linux.

text
python -m venv .venv
.venv/bin/python -c "import sys; print(sys.prefix != sys.base_prefix)"

The second command prints True. Here sys.prefix points to the venv and sys.base_prefix points to the base Python installation. Calling .venv/bin/python directly selects the environment without activating it in your shell.

In code, the same comparison tells a program whether it runs inside a venv. Run with the Python installed on the machine (not a venv), it prints:

python
import sys

in_venv = sys.prefix != sys.base_prefix
print(in_venv)
# prints: False

For a project managed by uv, put pyproject.toml beside the orbit directory. The [project] section describes the application and its requirements. The dev group lists development tools. This project uses Ruff to catch problems such as unused imports.

text
[project]
name = "orbit-cli"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = []

[dependency-groups]
dev = ["ruff"]

Run these commands from the directory containing pyproject.toml:

text
uv sync
uv run ruff check .

On the first run, uv sync selects compatible versions, records them in uv.lock and syncs the libraries into .venv. It includes the dev group by default. Keep uv.lock alongside pyproject.toml in Git so others can recreate the environment with the selected versions. The second command runs Ruff in the project environment. The dot tells Ruff to check the current directory.

Key takeaways

  • If an import loads the wrong file, check the module search path and local filenames.
  • Put the startup call under if __name__ == "__main__": so callers can import individual functions.
  • Read pyproject.toml for the project's requirements and uv.lock for the versions uv selected.

Sources