Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
kevinjwalters opened this issue Mar 24, 2025 · 2 comments
Open

Comments

@kevinjwalters
Copy link

kevinjwalters commented Mar 24, 2025

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.

@dflook
Copy link
Owner

dflook commented Mar 24, 2025

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.

@kevinjwalters
Copy link
Author

kevinjwalters commented Mar 26, 2025

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 > $@

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants