python-minifier icon indicating copy to clipboard operation
python-minifier copied to clipboard

Renaming globals isn't aware of imports from local source files

Open kevinjwalters opened this issue 9 months ago • 2 comments

If you have multiple files with and import statements then --rename-globals cannot be used.

For the files program.py

from library1 import NUMBER
import library2
instance = library2.SomethingClass()
print(NUMBER)

and library1.py

A=1.234

and library2.py

class SomethingClass():
    def __init__(self):
        self.name = "something"

these arguments

pyminify --remove-literal-statements --rename-globals --in-place program.py library1.py library2.py

produce output that does not work.

from library1 import NUMBER as A
import library2 as B
C=B.SomethingClass()
print(A)
A=1.234
class A:
        def __init__(A):A._name='something'

One workaround here is to always import things with from and do a hacky, fragile grep of that to produce symbols to be excluded using --preserve-globals.

I'm using this on some MicroPython code to squeeze it into a small file system on the micro:bit and apart from this and maybe some issues with MicroPython's special const() it works really well, thanks.

kevinjwalters avatar Mar 24 '25 00:03 kevinjwalters

Hello @kevinjwalters, thanks for creating an issue.

This is expected, as python-minifier only work on a single module at a time. It doesn't track names across modules. Using --rename-globals on a module is likely to break anything that imports it.

In this simple example, you could use --rename-globals for program.py, but not for the other files.

Minifying a whole program at a time would be a good enhancement.

dflook avatar Mar 24 '25 09:03 dflook

Thanks, my workaround is based on this primitive rule in my Makefile which "parses" all the from style imports so I can then exclude them with --preserve-globals.

global.symbols: $(ORIGINALS)
        sed -n 's/^from.*import //p' $^ | tr ',' '\012' | tr -d ' ' | sort -u > $@

kevinjwalters avatar Mar 26 '25 11:03 kevinjwalters