pyi-deps 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyi_deps/__init__.py ADDED
@@ -0,0 +1,188 @@
1
+ """Collect the imports of a staged Python tree so PyInstaller can see them.
2
+
3
+ PyInstaller's analysis starts at the entry script and follows ``import``
4
+ statements statically. That misses two common setups:
5
+
6
+ * scripts executed with ``runpy`` (a launcher loads them by path), and
7
+ * imports resolved at runtime by a plugin mechanism.
8
+
9
+ Both fail the same way: the app runs fine from source, then the frozen build
10
+ dies with ``ModuleNotFoundError`` on first use. The usual fix is a hand-written
11
+ list of hidden imports — which drifts the moment somebody adds an import.
12
+
13
+ This module replaces the list with a scan: parse every ``.py`` file under a
14
+ root, collect ``import x`` and ``from x import y``, drop local modules and
15
+ anything you asked to exclude, and emit a generated module that imports the
16
+ rest. PyInstaller sees the generated module because it is imported by the entry
17
+ script; the imports are real, so nothing has to be kept in sync by hand.
18
+
19
+ python -m pyi_deps --root src/runtime --out build/_deps.py
20
+
21
+ A subtlety worth the code: ``from Crypto.Cipher import AES`` names a module,
22
+ not an attribute, and PyInstaller will bundle ``Crypto.Cipher`` but not
23
+ ``AES``. The scanner checks each imported name with :func:`importlib.util.find_spec`
24
+ and adds ``Crypto.Cipher.AES`` when it resolves.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import ast
31
+ import importlib.util
32
+ import sys
33
+ from pathlib import Path
34
+ from typing import Iterable, Sequence
35
+
36
+ __all__ = ["scan", "render", "main"]
37
+
38
+ HEADER = (
39
+ "# Generated by pyi_deps -- do not edit.\n"
40
+ "# Imported by the entry script so PyInstaller's static analysis sees these.\n"
41
+ )
42
+
43
+
44
+ def _submodule_exists(name: str) -> bool:
45
+ try:
46
+ return importlib.util.find_spec(name) is not None
47
+ except (ImportError, AttributeError, ValueError):
48
+ return False
49
+
50
+
51
+ def _is_excluded(name: str, prefixes: Sequence[str]) -> bool:
52
+ return any(name == p or name.startswith(p + ".") for p in prefixes)
53
+
54
+
55
+ def _stdlib_names() -> frozenset:
56
+ """Top-level standard library modules, for filtering the output."""
57
+ names = getattr(sys, "stdlib_module_names", None) # Python 3.10+
58
+ if names is not None:
59
+ return frozenset(names)
60
+ # 3.9 has no sys.stdlib_module_names; this list only needs to cover what a
61
+ # normal project imports, and a miss here costs one harmless extra import.
62
+ return frozenset({
63
+ "abc", "argparse", "array", "ast", "asyncio", "base64", "binascii", "bisect",
64
+ "builtins", "bz2", "calendar", "codecs", "collections", "concurrent", "configparser",
65
+ "contextlib", "copy", "csv", "ctypes", "dataclasses", "datetime", "decimal", "difflib",
66
+ "dis", "email", "enum", "errno", "faulthandler", "filecmp", "fileinput", "fnmatch",
67
+ "fractions", "ftplib", "functools", "gc", "getopt", "getpass", "gettext", "glob",
68
+ "gzip", "hashlib", "heapq", "hmac", "html", "http", "imaplib", "importlib", "inspect",
69
+ "io", "ipaddress", "itertools", "json", "keyword", "linecache", "locale", "logging",
70
+ "lzma", "mailbox", "math", "mimetypes", "multiprocessing", "netrc", "numbers",
71
+ "operator", "os", "pathlib", "pickle", "pkgutil", "platform", "plistlib", "pprint",
72
+ "queue", "random", "re", "readline", "secrets", "select", "selectors", "shlex",
73
+ "shutil", "signal", "site", "smtplib", "socket", "sqlite3", "ssl", "stat", "statistics",
74
+ "string", "struct", "subprocess", "sys", "sysconfig", "tarfile", "tempfile", "textwrap",
75
+ "threading", "time", "timeit", "tkinter", "token", "tokenize", "traceback", "types",
76
+ "typing", "unicodedata", "unittest", "urllib", "uuid", "venv", "warnings", "wave",
77
+ "weakref", "webbrowser", "xml", "zipfile", "zipimport", "zlib",
78
+ })
79
+
80
+
81
+ def scan(root: str | Path, *, local_modules: Iterable[str] = (),
82
+ exclude_prefixes: Iterable[str] = (), resolve_submodules: bool = True,
83
+ include_stdlib: bool = False) -> list[str]:
84
+ """Return every import found under *root*, sorted and unique.
85
+
86
+ Standard library names are dropped by default: the generated module is meant
87
+ to list third-party dependencies, and ``import os`` in it is only noise.
88
+
89
+ ``local_modules`` are top-level names that live next to the scanned files and
90
+ are resolved by the runtime itself; excluding them keeps the generated module
91
+ importable outside the frozen build.
92
+
93
+ ``resolve_submodules`` controls the ``from package import module`` heuristic;
94
+ it needs the packages to be importable on the machine doing the scan, so turn
95
+ it off when cross-building. That heuristic uses
96
+ :func:`importlib.util.find_spec`, which imports the parent package — run it in
97
+ the same throwaway environment you build in.
98
+ """
99
+ local = set(local_modules)
100
+ excludes = tuple(exclude_prefixes)
101
+ stdlib = frozenset() if include_stdlib else _stdlib_names()
102
+ names: set[str] = set()
103
+
104
+ for path in sorted(Path(root).rglob("*.py")):
105
+ if "__pycache__" in path.parts:
106
+ continue
107
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
108
+ for node in ast.walk(tree):
109
+ if isinstance(node, ast.Import):
110
+ for alias in node.names:
111
+ names.add(alias.name)
112
+ elif isinstance(node, ast.ImportFrom):
113
+ # level > 0 is a relative import: it stays inside the package.
114
+ if node.level or not node.module:
115
+ continue
116
+ names.add(node.module)
117
+ if not resolve_submodules:
118
+ continue
119
+ for alias in node.names:
120
+ if alias.name == "*":
121
+ continue
122
+ full = node.module + "." + alias.name
123
+ if _submodule_exists(full):
124
+ names.add(full)
125
+
126
+ return sorted(
127
+ n for n in names
128
+ if n.split(".")[0] not in local
129
+ and n.split(".")[0] not in stdlib
130
+ and not _is_excluded(n, excludes)
131
+ )
132
+
133
+
134
+ def render(names: Iterable[str]) -> str:
135
+ """Render the generated module source.
136
+
137
+ Every import is wrapped in its own ``try/except ImportError``. The scan cannot
138
+ tell an import that is required from one the code guards with
139
+ ``try: import x / except ImportError``, and a bare ``import x`` in this file
140
+ would turn every optional dependency into a hard requirement — the generated
141
+ module is imported by the entry script, so a missing package would abort
142
+ startup before the app's own guard ever runs.
143
+
144
+ PyInstaller is not affected: it analyses imports statically, and an import
145
+ inside a ``try`` block is still seen and still pulled into the bundle. One
146
+ ``try`` per name, not one around the block, because a single missing package
147
+ would otherwise skip every import after it.
148
+ """
149
+ body = "".join(
150
+ "try:\n"
151
+ f" import {name} # noqa: F401\n"
152
+ "except ImportError:\n"
153
+ " pass # optional dependency: PyInstaller still sees the import\n"
154
+ for name in names
155
+ )
156
+ return HEADER + body
157
+
158
+
159
+ def main(argv: list[str] | None = None) -> int:
160
+ parser = argparse.ArgumentParser(
161
+ prog="pyi_deps", description="Scan a staged tree and emit a PyInstaller deps module."
162
+ )
163
+ parser.add_argument("--root", required=True, help="directory to scan recursively")
164
+ parser.add_argument("--out", required=True, help="path of the generated .py file")
165
+ parser.add_argument("--local", action="append", default=[],
166
+ help="local module name to ignore (repeatable)")
167
+ parser.add_argument("--exclude", action="append", default=[],
168
+ help="import prefix to exclude, e.g. PIL (repeatable)")
169
+ parser.add_argument("--no-submodules", action="store_true",
170
+ help="skip the 'from package import module' resolution")
171
+ parser.add_argument("--include-stdlib", action="store_true",
172
+ help="also list standard library modules (off by default)")
173
+ args = parser.parse_args(argv)
174
+
175
+ names = scan(args.root, local_modules=args.local, exclude_prefixes=args.exclude,
176
+ resolve_submodules=not args.no_submodules,
177
+ include_stdlib=args.include_stdlib)
178
+ out = Path(args.out)
179
+ out.parent.mkdir(parents=True, exist_ok=True)
180
+ # Path.write_text(newline=...) only exists from 3.10; Path.open does the job on 3.9.
181
+ with out.open("w", encoding="utf-8", newline="\n") as handle:
182
+ handle.write(render(names))
183
+ print(f"pyi_deps: {len(names)} imports -> {out}")
184
+ return 0
185
+
186
+
187
+ if __name__ == "__main__":
188
+ sys.exit(main())
@@ -0,0 +1,192 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyi-deps
3
+ Version: 0.1.0
4
+ Summary: Generate PyInstaller hidden imports by scanning a staged Python tree
5
+ Author: suimajian
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/suimajian/pyi-deps
8
+ Keywords: pyinstaller,packaging,hiddenimports,frozen
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Dynamic: license-file
13
+
14
+ # pyi-deps
15
+
16
+ Generate the `hiddenimports` list PyInstaller cannot see for itself, by parsing
17
+ the code instead of trusting a hand-written list.
18
+
19
+ ## Install
20
+
21
+ Not on PyPI yet — `pip install pyi-deps` will 404 until 0.1.0 is published.
22
+ Install from the repository instead:
23
+
24
+ ```bash
25
+ pip install git+https://github.com/suimajian/pyi-deps
26
+ ```
27
+
28
+ The sdist and wheel are attached to the
29
+ [releases](https://github.com/suimajian/pyi-deps/releases); the publish step is
30
+ waiting for credentials, so nothing has been uploaded to the index.
31
+
32
+ ## Use
33
+
34
+ ```bash
35
+ python -m pyi_deps --root src/runtime --out build/_deps.py
36
+ ```
37
+
38
+ ```python
39
+ # build/_deps.py — generated, imported by the entry script
40
+ # Generated by pyi_deps -- do not edit.
41
+ # Imported by the entry script so PyInstaller's static analysis sees these.
42
+ try:
43
+ import bs4 # noqa: F401
44
+ except ImportError:
45
+ pass
46
+ try:
47
+ import requests # noqa: F401
48
+ except ImportError:
49
+ pass
50
+ try:
51
+ import tiktoken # noqa: F401
52
+ except ImportError:
53
+ pass
54
+ ```
55
+
56
+ ## The problem it solves
57
+
58
+ PyInstaller freezes an app by walking `import` statements from the entry script.
59
+ Anything it cannot see statically has to be named by hand:
60
+
61
+ | Setup | What PyInstaller sees |
62
+ | --- | --- |
63
+ | `import x` in the entry script | yes |
64
+ | `import x` in a module the entry script imports | yes |
65
+ | `runpy.run_path("runtime/main.py")` | **nothing inside that file** |
66
+ | `importlib.import_module(name)` from a plugin table | **no** |
67
+
68
+ The third row is the common one for launchers: one small entry script, the real
69
+ code shipped as loose files next to it. The build works, then the installed app
70
+ dies with `ModuleNotFoundError: No module named 'logging.handlers'` on a code
71
+ path nobody exercised during the smoke test.
72
+
73
+ The fix everyone reaches for is a manually maintained hidden-import list. It is
74
+ correct the day it is written and wrong the first time someone in the runtime
75
+ tree adds an import — with no test failing, because the failure only appears in
76
+ a frozen build.
77
+
78
+ This tool turns that list into a scan. The generated module is imported by the
79
+ entry script, so PyInstaller's normal analysis picks the imports up from there:
80
+
81
+ ```python
82
+ # entry script
83
+ import _deps # noqa: F401 (generated at build time)
84
+ ```
85
+
86
+ ## Usage
87
+
88
+ ```bash
89
+ # in the build script, right before PyInstaller runs
90
+ python -m pyi_deps --root stage/runtime --out stage/_deps.py \
91
+ --local app --local config \
92
+ --exclude PIL
93
+ ```
94
+
95
+ | Flag | Meaning |
96
+ | --- | --- |
97
+ | `--root` | directory to scan recursively (`.py` only, `__pycache__` skipped) |
98
+ | `--out` | where to write the generated module |
99
+ | `--local` | top-level name that is part of the app, so never emitted (repeatable) |
100
+ | `--exclude` | import prefix to leave out of the build, e.g. `PIL` (repeatable) |
101
+ | `--no-submodules` | skip `from package import module` resolution (cross-builds) |
102
+ | `--include-stdlib` | also list `os`, `json`, … (off by default: the generated file is for dependencies) |
103
+
104
+ ## Every import is wrapped in `try/except`
105
+
106
+ The scan cannot tell a required import from one the code guards itself:
107
+
108
+ ```python
109
+ try:
110
+ import win32api # optional on this platform
111
+ except ImportError:
112
+ win32api = None
113
+ ```
114
+
115
+ A bare `import win32api` in the generated module would turn that optional
116
+ dependency into a hard requirement — and because the entry script imports the
117
+ generated module, the app would die at startup on exactly the machines the guard
118
+ was written for. So each name gets its own `try` block:
119
+
120
+ ```python
121
+ try:
122
+ import win32api # noqa: F401
123
+ except ImportError:
124
+ pass # optional dependency: PyInstaller still sees the import
125
+ ```
126
+
127
+ PyInstaller's analysis is static, so an import inside a `try` is still found and
128
+ still bundled; only the runtime behaviour changes. One `try` per name, not one
129
+ around the block: otherwise the first missing package would skip all the rest.
130
+
131
+ As a library:
132
+
133
+ ```python
134
+ from pyi_deps import scan, render
135
+
136
+ names = scan("stage/runtime", local_modules={"app"}, exclude_prefixes=("PIL",))
137
+ Path("stage/_deps.py").write_text(render(names), encoding="utf-8")
138
+ ```
139
+
140
+ ## The submodule detail
141
+
142
+ `from Crypto.Cipher import AES` imports **a module**, not an attribute. PyInstaller
143
+ bundles `Crypto.Cipher` and the binding then fails at runtime, because `AES` is a
144
+ separate extension. The scanner asks `importlib.util.find_spec` whether each
145
+ imported name resolves to a module and, if so, emits the full dotted path
146
+ (`Crypto.Cipher.AES`) as well.
147
+
148
+ That check needs the packages installed on the scanning machine, which is why
149
+ `--no-submodules` exists for cross-builds. Note what it does: `find_spec("a.b.c")`
150
+ **imports `a.b`** to look inside it, so a package with import-time side effects
151
+ (reads config, opens a connection) runs them during the scan. Do the scan in the
152
+ same throwaway environment you build in, or pass `--no-submodules` and accept
153
+ losing the submodule hint.
154
+
155
+ ## Limits
156
+
157
+ - Only static `import` / `from ... import` statements. `importlib.import_module(var)`
158
+ with a runtime-computed name is still your problem.
159
+ - It collects *names*, not versions. Pair it with a pinned requirements file.
160
+ - A syntax error in the tree is surfaced, not skipped: a broken file at build
161
+ time is better than a missing import at run time.
162
+ - Standard library names are filtered out by default (`--include-stdlib` keeps
163
+ them). They are already bundled; listing them only hides the real ones.
164
+ - Relative imports (`from . import x`) are ignored — a staged build directory has
165
+ no package context to resolve them against.
166
+ - It does not read the installed distributions' `top_level.txt`; what is on disk
167
+ under the scanned root is what gets listed.
168
+
169
+ ## Scope and non-goals
170
+
171
+ - **Not a packaging tool.** It writes one module of `try: import x` lines and
172
+ stops. No hooks, no spec files, no version pinning.
173
+ - **Not a sandbox.** `find_spec` may import parent packages, so scan inside the
174
+ same throwaway environment you build in.
175
+ - **No import-time validation of your code** — that is what `pytest` and running
176
+ the frozen build are for.
177
+
178
+ ## Status
179
+
180
+ 0.1.0 — not on PyPI yet. A tag (`v*`) builds sdist + wheel and uploads them as a
181
+ workflow artifact; the publish step only runs when a `PYPI_API_TOKEN` repository
182
+ secret exists, so nothing is published by accident.
183
+
184
+ ## Tests
185
+
186
+ ```bash
187
+ python -m pytest -q
188
+ ```
189
+
190
+ ## Licence
191
+
192
+ MIT.
@@ -0,0 +1,7 @@
1
+ pyi_deps/__init__.py,sha256=w99YdHTN6aqGcs5nxSVkJbm3Hlu0i3Ok6sQQnTzIwO8,8643
2
+ pyi_deps-0.1.0.dist-info/licenses/LICENSE,sha256=3zJsa_ylIITLNIbTT7jWBjxzTN0n46bsm9IF17b2VCo,1066
3
+ pyi_deps-0.1.0.dist-info/METADATA,sha256=tncuoS4A79sJ32mL-MB09_AKxJQzkp8gvb7O1pqXwEA,6705
4
+ pyi_deps-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ pyi_deps-0.1.0.dist-info/entry_points.txt,sha256=ogZyybLbIwsY1aVtDCN40pUTJDWMet0sCo1b6AzgnkA,43
6
+ pyi_deps-0.1.0.dist-info/top_level.txt,sha256=LbguOGDtKpg263jAratcAL-4Qsq_yoUYcAxUjE7yYMk,9
7
+ pyi_deps-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pyi-deps = pyi_deps:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 suimajian
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ pyi_deps