Unit 8 of 9 · about 4 hours · explain, implement
Imports, virtual environments and src-layout packaging
The checkpoint builds and installs a package. Import evidence is also how every environment bug gets diagnosed.
You'll be able to
- Explain module caching, path resolution and package boundaries, including script versus
-mexecution. - Diagnose import shadowing and environment mismatch from
sys.pathandsys.modulesevidence. - Build and install a typed src-layout package from a blank directory with a console entry point, verified in a clean environment.
Covers
Read
In this order, only the parts listed
0 of 8 done
- Import search pathStas' Python Cookbook - selected path
Modules and Imports:
sys.pathorder; computing paths from__file__;PYTHONPATH - Module cache and dynamic importStas' Python Cookbook - selected path
Inspecting and reloading modules (the
sys.modulescache;reloadkeeps old objects) and Dynamic import withimportlib - The module cache and packagesPython language reference
Section 5.3.1 The module cache (one execution per process); 5.2 Packages (regular versus namespace); 5.7 relative imports
- Searching and __main__Python language reference
Section 5.3 Searching with 5.5 Path Based Finder; 5.8
__main__(script versus-mpath and the double-execution trap) - Environment variables and argparseStas' Python Cookbook - selected path
Environment Variables and Program Arguments:
environhandling; theargparseCLI shape; replaying the exact command line - Versions and virtual environmentsStas' Python Cookbook - selected path
Versions and Dependencies:
sys.version_infochecks,importlib.metadataversions,venvcreation and activation - Creating the package filesPackaging Python Projects
Creating the package files (the
srclayout tree) through Configuring metadata; choose thesetuptoolsbackend - Building and installing locallyPackaging Python Projects
Generating distribution archives (one build produces sdist and wheel) and Installing your newly uploaded package
Skip Uploading the distribution archives; do not publish to TestPyPI. Install from
dist/into a cleanvenvinstead (verified with asetuptools-backend build and a clean-environment wheel install).
Focus on
- Importing executes the module once per process and caches it in
sys.modules. A second import binds the same object;reload()re-executes but old objects keep old classes. sys.path[0]differs by launch: a script prepends its own directory while-mprepends the current directory. The same file run as a script and imported as a module executes twice, as__main__and under its real name.- Regular packages need
__init__.py; namespace packages merge path portions without one. Relative imports need package context and fail in bare scripts. - Editable installs register the project in the environment; path hacks only fake it. The passing test is a clean-environment install with no
sys.pathedits.
Common mistakes · 3
- Running tests from the package directory and importing the local tree by accident. The clean-environment install test exists to catch exactly this.
- Two copies of one module: tests
import pkg.modwhile a script already ran it as__main__. State lives in two places and singletons split. - Using
pip freezefor requirements. It captures the whole environment; record direct dependencies and verify with the clean install.
Try it yourself
Closed-book, before checking anything
atlas_demo with an add() function and an atlas-demo entry point; build the sdist and wheel; install the wheel in a clean environment and run the entry point to print 5 with no sys.path edits.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.
import pkg.modruns twice in one process. How many executions happen, and how do you prove it?AnswerOne. The second import rebinds from
sys.modules; the new name issys.modules['pkg.mod'].2.Why does
python sub/show.pydiffer frompython -m sub.showinsys.path[0]?AnswerThe script prepends its own directory;
-mprepends the current directory. Imports resolve differently from each.3.A script imports its sibling fine but fails after moving to a
srclayout. What changed?AnswerThe sibling is no longer on
sys.pathand implicit siblings are gone. Install the package or run from a layout that putssrcon the path; do not hand-editsys.pathas the fix.4.What distinguishes an editable install from a
PYTHONPATHhack?AnswerThe editable install registers package metadata and entry points in the environment;
PYTHONPATHonly shadows imports and leaves every other machine broken.
Practice
- AlgoMaster Python: Exercise: Packages
Exercises 1 to 5, especially Exercise 3: Re-export a Flat Package API and Exercise 4: Use Relative Imports in a Subpackage
Do it after building the tutorial package; compare its layout with yours.
- AlgoMaster Python: Exercise: Virtual Environments
Exercises 1 to 5, especially Exercise 2: Read
pyvenv.cfgSettings and Exercise 5: Audit a Venv Against RequirementsCreate the clean install-test venv from memory.
You're done when
Your entry point runs from a clean environment, and you can name sys.path[0] and the cached module for any launch.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 5 more in the section
- Stas' Python Cookbook - selected pathStas Bekman · primary
Run Part I on dictionaries, iteration, functions, closures, decorators, classes and context managers; Part II on modules, files, paths, environment and arguments; and Part IV on versions, dependencies, packaging and code quality. Finish by building one src-layout package from a blank directory.
- Python language referencePython Software Foundation · required
Check Data model, Execution model, Import system and Exceptions whenever a claim depends on Python semantics. These pages are the authority when the course and a runtime observation disagree.
- Packaging Python ProjectsPython Packaging Authority · required
Follow the packaging tutorial once from a blank directory, using a src layout, pyproject.toml, an isolated build and a clean-environment installation test.
Also in this section
- AlgoMaster Python - structured revisionAlgoMaster · support
Use Functions, Modules and Packages, OOP, Advanced OOP, Exception Handling, Iterators and Generators, Type Hints and Annotations only after the cookbook pass. Open it for recall practice or a diagnosed weak mechanism, not as a second complete course.
- dataclasses - data classesPython Software Foundation · reference
Read the
@dataclassparameters (eq,order,frozen,slots),field()withdefault_factory, frozen instances, post-init processing,replace,asdictandastuple. Use for the validated frozen dataclass in attributes-protocols-dataclasses. - typing - type hints and protocolsPython Software Foundation · reference
Read Protocols for structural typing and
runtime_checkablelimits, Generics forTypeVargenerics, andassert_typefor narrowing checks. Use for theProtocoland narrowing parts of type-hints-protocols; PEP 695 syntax itself is in the language reference. - gc - cycle garbage collectorPython Software Foundation · reference
Read the cycle collector interface:
collect,get_count,garbageanddisable/enable. Use for the cycle-collection and measurement parts of refcounting-gc-weakrefs. - weakref - weak referencesPython Software Foundation · reference
Read weak-reference objects (
refcallbacks,proxyobjects) and theWeakValueDictionaryexample. Use for the weak-reference part of refcounting-gc-weakrefs.