How to programmatically determine the minimum set of files required to import a given Python module?

67 views Asked by At

I'm working on a Python3 script that uses pyobjc to access the macOS clipboard via NSPasteboard. To do this, it requires the following import:

from AppKit import NSPasteboard

In order to keep my distribution to a minimum size (the full pyobjc 9.2 package is 30MB), I wanted to find out the smallest set of files needed in order to allow this import to succeed. Through trial-and-error (using a REPL and attempting to import NSPasteboard, looking at the stack trace errors and adding in missing modules one by one), I determined this to be:

./lib
├── AppKit
├── CoreFoundation
├── Foundation
├── objc
└── PyObjCTools

This slimmed set is only 7MB by comparison.

My question is: is there a more pragmatic way to determine this? Using importlib or something similar?

1

There are 1 answers

3
Philippe On

These commands give minimum imports :

python -v -c "from AppKit import NSPasteboard" |&\
    perl -ne 'print "$1\n" if (/^import '"'"'([^'"'"'.]+)/)' | sort -u

Update

This script gets the minimum required:

#!/usr/bin/env bash

dir=/tmp/lib
python3 -m pip install --isolated --target=$dir pyobjc
for c in $(python -v -c "from AppKit import NSPasteboard" 2>&1 |
    perl -ne 'print "$1\n" if (/^import '"'"'([^'"'"'.]+)/)' | sort -u); do
    test -d $dir/$c && echo $c
done