-
-
Save mikalstill/9b183dfa0a6f17c8be2af6b83752441a to your computer and use it in GitHub Desktop.
A Python import bloat finder helper script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # Copyright 2026 Michael Still and contributors | |
| """Measure what a Python process's imports cost it, and which import pulled each package in. | |
| Most of a long-running Python service's steady-state memory is the code it | |
| imported, not the data it holds, so a package a process loads but never calls | |
| costs real memory in every process that loads it. This tool measures that, in | |
| a fresh interpreter per measurement, from /proc/self/status (Linux only). | |
| import-bloat probe [--path DIR]... ROLE MODULE [MODULE ...] | |
| import-bloat roles [--path DIR]... [--roles REGEX] [--python PY] ROLES_FILE | |
| import-bloat marginal [--path DIR]... BASE[,BASE...] TARGET[,TARGET...] | |
| import-bloat report PROBE.jsonl [--packages a,b] [--chain PACKAGE] [--min-modules N] | |
| import-bloat compare BEFORE.jsonl AFTER.jsonl [AFTER.jsonl ...] [--packages a,b] | |
| probe imports each MODULE in order and prints one JSON line: anonymous and | |
| total RSS (MB) before and after, the module count, the module count per | |
| top-level package, any import errors, and for each top-level package the chain | |
| of modules that were running when it first loaded, innermost first. A MODULE | |
| of the form call:pkg.mod.fn runs pkg.mod.fn() after importing pkg.mod, for | |
| setup an entry point does before it imports the rest (registering objects, | |
| choosing a backend). The call may carry literal arguments, | |
| call:pkg.mod.fn(1,key='v'), which are parsed with ast.literal_eval and never | |
| evaluated; write no spaces inside. An import error is recorded, not fatal, so | |
| a role whose last plugin fails still reports what it loaded. | |
| roles runs probe once per line of ROLES_FILE, each in its own `PY -I` | |
| interpreter (PY defaults to this interpreter), and prints one JSON line per | |
| role. A line is `ROLE MODULE [MODULE ...]`; # starts a comment. --roles keeps | |
| only roles whose name matches the regular expression. | |
| marginal imports BASE, then TARGET, and prints the anonymous RSS and module | |
| count TARGET added. Choose a BASE the process loads anyway, so the figure is | |
| what not importing TARGET would save rather than the cost of dependencies the | |
| process needs regardless. Run it in a fresh interpreter (python -I). | |
| report summarises probe output: a row per role, then a package-by-role table | |
| of module counts ('.' for none), or with --chain the import chain for one | |
| package in each role. | |
| compare prints anonymous RSS per role for a before run and one or more after | |
| runs, with the saving against the before run, and with --packages the module | |
| counts of those packages in each run. Every after run is compared with the | |
| same before run, so the savings can never use mixed baselines. | |
| --path DIR puts DIR at the front of sys.path, to probe a source tree without | |
| installing it. probe, roles and marginal must run with python -I, so that | |
| nothing the environment imports first is attributed; roles does that itself. | |
| """ | |
| import argparse | |
| import ast | |
| import collections | |
| import importlib | |
| import importlib.abc | |
| import json | |
| import os | |
| import re | |
| import subprocess | |
| import sys | |
| def status_kb(): | |
| """Return this process's VmRSS and RssAnon in kB.""" | |
| out = {} | |
| with open('/proc/self/status') as f: | |
| for line in f: | |
| key, _, value = line.partition(':') | |
| if key in ('VmRSS', 'RssAnon'): | |
| out[key] = int(value.split()[0]) | |
| return out | |
| def status(): | |
| """Return this process's VmRSS and RssAnon in whole MB.""" | |
| return {k: v // 1024 for k, v in status_kb().items()} | |
| # Frames that belong to the import machinery rather than to the importing code. | |
| # This script's own frames are recognised by their globals, not their filename, | |
| # which differs from __file__ when the script is reached through a symlink. | |
| # importlib.metadata and importlib.resources are ordinary libraries, so only | |
| # the bootstrap and importlib.import_module itself are skipped. | |
| _IMPORTLIB = os.path.dirname(importlib.__file__) | |
| _MACHINERY = ('<frozen importlib._bootstrap', os.path.join(_IMPORTLIB, '_bootstrap'), | |
| os.path.join(_IMPORTLIB, '__init__.py')) | |
| class ChainRecorder(importlib.abc.MetaPathFinder): | |
| """Record, for each module, the modules that were running when it was first imported. | |
| A finder at the front of sys.meta_path sees every import, whether it comes | |
| from an import statement, importlib.import_module or a plugin loader. It | |
| never finds anything itself; it notes the stack and lets the real finders | |
| run. Only modules that end up in sys.modules are reported, and a later | |
| lookup replaces the stack of one that has not loaded yet. So a library | |
| that only checks whether eventlet is installed, with | |
| importlib.util.find_spec(), or that tries an import which fails, is not | |
| blamed when something else loads eventlet later. | |
| """ | |
| def __init__(self): | |
| self.chains = {} | |
| self.order = [] | |
| def find_spec(self, name, path=None, target=None): | |
| if name in sys.modules: | |
| return None | |
| frame = sys._getframe(1) | |
| chain = [] | |
| while frame is not None: | |
| filename = frame.f_code.co_filename | |
| if not filename.startswith(_MACHINERY) and frame.f_globals is not globals(): | |
| module = frame.f_globals.get('__name__', '?') | |
| if not chain or chain[-1] != module: | |
| chain.append(module) | |
| frame = frame.f_back | |
| if name not in self.chains: | |
| self.order.append(name) | |
| self.chains[name] = [name] + chain | |
| return None | |
| def run_call(spec): | |
| """Run 'pkg.mod.fn' or 'pkg.mod.fn(literal, key=literal)'.""" | |
| name, args, kwargs = spec, [], {} | |
| if '(' in spec: | |
| node = ast.parse(spec, mode='eval').body | |
| if not isinstance(node, ast.Call) or any(isinstance(a, ast.Starred) for a in node.args): | |
| raise ValueError('not a plain call: %s' % spec) | |
| name = spec[:spec.index('(')] | |
| args = [ast.literal_eval(a) for a in node.args] | |
| kwargs = {k.arg: ast.literal_eval(k.value) for k in node.keywords} | |
| module, _, function = name.rpartition('.') | |
| getattr(importlib.import_module(module), function)(*args, **kwargs) | |
| def probe(role, modules): | |
| recorder = ChainRecorder() | |
| sys.meta_path.insert(0, recorder) | |
| base = status() | |
| errors = {} | |
| for m in modules: | |
| try: | |
| if m.startswith('call:'): | |
| run_call(m[len('call:'):]) | |
| else: | |
| importlib.import_module(m) | |
| except Exception as e: | |
| errors[m] = '%s: %s' % (type(e).__name__, e) | |
| after = status() | |
| sys.meta_path.remove(recorder) | |
| loaded = [m for m in list(sys.modules) if sys.modules[m] is not None] | |
| tops = collections.Counter(m.split('.')[0] for m in loaded) | |
| chains = {} | |
| for name in recorder.order: | |
| top = name.split('.')[0] | |
| if top not in chains and name in sys.modules: | |
| chains[top] = recorder.chains[name] | |
| return {'role': role, 'base': base, 'after': after, 'errors': errors, | |
| 'nmodules': len(loaded), 'packages': dict(tops), 'chains': chains} | |
| def marginal(base, target): | |
| for m in [m for m in base.split(',') if m]: | |
| importlib.import_module(m) | |
| before, nbefore = status_kb()['RssAnon'], len(sys.modules) | |
| for m in [m for m in target.split(',') if m]: | |
| importlib.import_module(m) | |
| return {'base': base, 'target': target, 'anon_mb': (status_kb()['RssAnon'] - before) / 1024, | |
| 'modules': len(sys.modules) - nbefore} | |
| def read_roles(path, pattern=None): | |
| roles = [] | |
| with open(path) as f: | |
| for line in f: | |
| words = line.split('#', 1)[0].split() | |
| if words and (pattern is None or re.search(pattern, words[0])): | |
| roles.append(words) | |
| return roles | |
| def read_probe(path): | |
| with open(path) as f: | |
| return [json.loads(line) for line in f if line.strip()] | |
| def short(role, width=7): | |
| return role[:width - 1] | |
| def report(rows, packages=None, chain=None, min_modules=20): | |
| out = [] | |
| if chain: | |
| for r in rows: | |
| if chain in r['chains']: | |
| out.append('%-26s %s' % (r['role'], ' <- '.join(r['chains'][chain]))) | |
| return out | |
| for r in rows: | |
| errors = list(r['errors'].values()) | |
| out.append('%-26s anon %4d MB rss %4d MB modules %5d %s' | |
| % (r['role'], r['after']['RssAnon'], r['after']['VmRSS'], r['nmodules'], | |
| ('ERROR ' + errors[0][:60]) if errors else '')) | |
| out.append('') | |
| if not packages: | |
| packages = sorted({p for r in rows for p, n in r['packages'].items() if n >= min_modules}) | |
| out.append('%-20s' % 'package' + ''.join('%7s' % short(r['role']) for r in rows)) | |
| for p in packages: | |
| counts = [r['packages'].get(p, 0) for r in rows] | |
| if any(counts): | |
| out.append('%-20s' % p[:20] + ''.join('%7s' % (n or '.') for n in counts)) | |
| return out | |
| def compare(names, runs, packages=None): | |
| """Return a table of anonymous RSS per role for a before run and each after run.""" | |
| before = {r['role']: r for r in runs[0]} | |
| afters = [{r['role']: r for r in run} for run in runs[1:]] | |
| labels = [os.path.basename(n).rsplit('.', 1)[0] for n in names] | |
| header = ['role', labels[0]] | |
| for label in labels[1:]: | |
| header += [label, 'saving'] | |
| lines = [header] | |
| for role, b in before.items(): | |
| line = [role, str(b['after']['RssAnon'])] | |
| for after in afters: | |
| a = after.get(role) | |
| if a is None: | |
| line += ['-', '-'] | |
| else: | |
| line += [str(a['after']['RssAnon']), str(b['after']['RssAnon'] - a['after']['RssAnon'])] | |
| if b['errors'] or any(after.get(role, {}).get('errors') for after in afters): | |
| line.append('ERROR') | |
| lines.append(line) | |
| out = _columns(lines) | |
| for p in packages or []: | |
| rows = [['%s modules' % p] + labels] | |
| for role in before: | |
| counts = [run.get(role, {}).get('packages', {}).get(p, 0) for run in [before] + afters] | |
| if any(counts): | |
| rows.append([role] + [str(n or '.') for n in counts]) | |
| out.append('') | |
| out += _columns(rows) if len(rows) > 1 else ['%s: not loaded in any run' % p] | |
| return out | |
| def _columns(lines): | |
| """Align rows of cells: the first column left, the rest right.""" | |
| widths = [max(len(line[i]) for line in lines if i < len(line)) for i in range(max(len(line) for line in lines))] | |
| return [' '.join(cell.rjust(widths[i]) if i else cell.ljust(widths[i]) for i, cell in enumerate(line)) | |
| for line in lines] | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0], | |
| formatter_class=argparse.RawDescriptionHelpFormatter) | |
| sub = parser.add_subparsers(dest='command', required=True) | |
| p = sub.add_parser('probe', help='import one role and print its memory, modules and chains') | |
| p.add_argument('--path', action='append', default=[]) | |
| p.add_argument('role') | |
| p.add_argument('modules', nargs='+') | |
| p = sub.add_parser('roles', help='probe every role in a roles file, each in a fresh interpreter') | |
| p.add_argument('--path', action='append', default=[]) | |
| p.add_argument('--roles', help='only roles whose name matches this regular expression') | |
| p.add_argument('--python', default=sys.executable, help='the interpreter to probe with') | |
| p.add_argument('roles_file') | |
| p = sub.add_parser('marginal', help='the anonymous RSS TARGET adds on top of BASE') | |
| p.add_argument('--path', action='append', default=[]) | |
| p.add_argument('base') | |
| p.add_argument('target') | |
| p = sub.add_parser('report', help='summarise probe output') | |
| p.add_argument('probe') | |
| p.add_argument('--packages', help='comma separated top-level packages for the table') | |
| p.add_argument('--chain', help='print the import chain for this top-level package') | |
| p.add_argument('--min-modules', type=int, default=20) | |
| p = sub.add_parser('compare', help='per-role savings of one or more after runs against a before run') | |
| p.add_argument('runs', nargs='+') | |
| p.add_argument('--packages', help='comma separated top-level packages to count in each run') | |
| args = parser.parse_args() | |
| for d in reversed(getattr(args, 'path', [])): | |
| sys.path.insert(0, os.path.abspath(d)) | |
| if args.command == 'probe': | |
| print(json.dumps(probe(args.role, args.modules))) | |
| elif args.command == 'marginal': | |
| r = marginal(args.base, args.target) | |
| print('%-55s +%5.1f MB +%4d modules' % (r['target'][:55], r['anon_mb'], r['modules'])) | |
| elif args.command == 'roles': | |
| paths = [a for d in args.path for a in ('--path', os.path.abspath(d))] | |
| for words in read_roles(args.roles_file, args.roles): | |
| result = subprocess.run([args.python, '-I', os.path.abspath(__file__), 'probe'] + paths + words, | |
| capture_output=True, text=True) | |
| lines = result.stdout.strip().splitlines() | |
| if result.returncode or not lines: | |
| print(json.dumps({'role': words[0], 'base': {}, 'after': {'RssAnon': 0, 'VmRSS': 0}, | |
| 'errors': {'probe': result.stderr.strip()[-300:]}, 'nmodules': 0, | |
| 'packages': {}, 'chains': {}})) | |
| else: | |
| print(lines[-1]) | |
| sys.stdout.flush() | |
| elif args.command == 'report': | |
| packages = args.packages.split(',') if args.packages else None | |
| print('\n'.join(report(read_probe(args.probe), packages, args.chain, args.min_modules))) | |
| elif args.command == 'compare': | |
| if len(args.runs) < 2: | |
| parser.error('compare needs a before run and at least one after run') | |
| packages = args.packages.split(',') if args.packages else None | |
| print('\n'.join(compare(args.runs, [read_probe(r) for r in args.runs], packages))) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment