basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    Chapter 12PythonBigger code

    Modules and packages: your own files, pip and virtual environments

    Any .py file is already a module you can load with import in another script. Install third-party libraries via pip into a separate .venv virtual environment so projects don’t break each other’s versions. Move port parsing into its own module, see how if __name__ == "__main__": works and rebuild an environment from requirements.txt.

    What you’ll get

    When a script grows, move reusable functions into a separate file. Place two files in the same folder — a module net_utils.py and a script check.py that uses it:

    # net_utils.py
    def parse_port(text):
        port = int(text)
        if not 1 <= port <= 65535:
            raise ValueError(f"port out of range 1..65535: {port}")
        return port
    
    
    if __name__ == "__main__":
        print("Module test:", parse_port("443"))
    # check.py
    from net_utils import parse_port
    
    for raw in ["22", "443", "8080"]:
        print(parse_port(raw))
    python check.py
    # 22
    # 443
    # 8080
    
    python net_utils.py
    # Module test: 443

    Running check.py never prints "Module test: 443". The if __name__ == "__main__": check runs only when you execute the file directly and is skipped on import.

    What will it print?
    # tools.py
    print("loaded:", __name__)
    
    # main.py — run: python main.py
    import tools
    What will it print?
    Answer:
    loaded: tools

    import runs the file top to bottom once to create its functions and variables. Inside an imported file, __name__ equals its module name ("tools"), while "__main__" belongs only to the file launched directly.

    How it works: where Python finds modules

    On import name, Python looks for name.py or a package folder name/ along the sys.path list from top to bottom:

    1. Script’s own folder      ──► net_utils.py (your files)
    2. Standard library         ──► pathlib, math, json, urllib, hashlib
    3. Third-party packages     ──► .venv/.../site-packages (from pip)

    Because your own folder comes first, a file named json.py or random.py shadows the standard library. Python 3.13+ explicitly suggests renaming such a file in its error message, though picking distinct filenames from the start avoids the clash altogether.

    Ways to import:

    Syntax How you call it When to use
    import math math.sqrt(16) keeps the module origin visible at every call site
    from pathlib import Path Path("logs") when you need one or two names from a module
    import urllib.request as req req.urlopen(url) short alias for a long module name
    from module import * — avoid: overwrites existing names and hides where functions came from

    Virtual environments: one .venv per project

    The standard library covers files, dates, JSON and basic HTTP requests. For tasks like generating QR codes, parsing YAML or talking to Telegram, install third-party packages from PyPI.

    Installing them into system Python leads to version conflicts between projects. Recent Ubuntu and Debian releases also block global pip install (PEP 668). Give each project its own .venv folder with its own packages:

    # create once in the project folder
    python -m venv .venv
    
    # Windows: install a package and run a script
    .venv\Scripts\python -m pip install qrcode
    .venv\Scripts\python app.py
    
    # Linux and macOS
    .venv/bin/python -m pip install qrcode
    .venv/bin/python app.py

    Activating the environment (activate) is optional: calling .venv\Scripts\python (or .venv/bin/python) picks up the right packages directory on its own and doesn’t depend on PowerShell’s execution policy. Run pip through python -m pip rather than bare pip so packages land in that exact interpreter, not another Python on PATH.

    Never commit .venv/ to git: list it in .gitignore and keep your dependencies in a text file instead.

    pip and requirements.txt

    Everyday pip commands (run through the python inside .venv):

    Command What it does
    python -m pip install qrcode installs the latest version from PyPI
    python -m pip install "qrcode==8.2" installs an exact version
    python -m pip list lists installed packages and versions in this environment
    python -m pip freeze > requirements.txt writes exact versions to a file for reproducing elsewhere
    python -m pip install -r requirements.txt installs the same versions on another machine or server
    python -m pip uninstall qrcode removes a package

    For a full walkthrough of creating .venv and installing a package on a real task, see Wi-Fi QR code.

    Take it further

    Move median(values) from Lists and tuples into stats_utils.py with an if __name__ == '__main__': guard and call it from report.py

    Put def median(values): and a test print under if __name__ == '__main__': in stats_utils.py; write from stats_utils import median in report.py.

    # stats_utils.py
    def median(values):
        s = sorted(values)
        mid = len(s) // 2
        if len(s) % 2:
            return s[mid]
        return (s[mid - 1] + s[mid]) / 2
    
    
    if __name__ == "__main__":
        print(median([23, 19, 87, 21, 20]))
    
    # report.py
    from stats_utils import median
    
    print("Median:", median([12, 45, 18, 22, 19]))
    Print every directory Python searches on import

    The list of paths lives in sys.path inside the standard sys module.

    import sys
    
    for path in sys.path:
        print(path)
    Create a .venv in an empty folder, list its packages and confirm sys.prefix points to .venv

    Create it with python -m venv .venv, then run the interpreter inside .venv with -m pip list and -c "import sys; print(sys.prefix)".

    python -m venv .venv
    
    # Windows
    .venv\Scripts\python -m pip list
    .venv\Scripts\python -c "import sys; print(sys.prefix)"
    
    # Linux and macOS
    .venv/bin/python -m pip list
    .venv/bin/python -c "import sys; print(sys.prefix)"

    If it doesn’t work

    ModuleNotFoundError: No module named 'httpx' for a package you already installed

    Cause
    The package is installed in .venv, but you ran the script with system python: each environment has its own packages folder.
    Fix
    Run the interpreter inside the environment: .venv\Scripts\python app.py on Windows or .venv/bin/python app.py on Linux and macOS.

    AttributeError: module 'json' has no attribute 'loads'

    Cause
    You gave your own file the same name as a standard library module or package — such as json.py or random.py. Python checks the current folder first and imports your file instead.
    Fix
    Rename your file (for example, parse_json.py) and delete the nearby __pycache__ folder if one was created.

    Importing your own module immediately prints its test output

    Cause
    print() calls and function calls sit at the top level of the file without an if __name__ == "__main__": guard.
    Fix
    Move the script entry code under if __name__ == "__main__": so importing only runs the function definitions.

    error: externally-managed-environment on pip install in Linux

    Cause
    Ubuntu 23.04+, Debian 12+ and other recent distributions lock system Python against third-party installs (PEP 668) to protect OS tools.
    Fix
    Create an environment with python3 -m venv .venv and install packages into it with .venv/bin/python -m pip install.

    The .venv folder ended up in a git repository

    Cause
    The environment wasn’t listed in .gitignore; it contains thousands of files tied to one OS and local paths.
    Fix
    Add .venv/ to .gitignore and commit only requirements.txt — any machine can recreate the environment from it.

    Also in this chapter