dflook / python-minifier

Transform Python source code into its most compact representation
MIT License
553 stars 40 forks source link

use f string = specifier #66

Closed ArztKlein closed 1 year ago

ArztKlein commented 1 year ago

Uses the f string = specifier when it would shorten. (only above python 3.8)

Example:

name = "John"
print("name=" + name)

becomes

name = "John"
print(f"{name=}")
ArztKlein commented 1 year ago

Need to fix the error and add tests later.

dflook commented 1 year ago

Hello @ArztKlein, thanks for looking at this.

We need to be careful how this interacts with renaming, we don't want to change the resulting string. With your example, the shortest code would be:

A="John"
print("name="+A)

This would be even shorter, but wrong:

A="John"
print(f"{A=}")

The = specifier is handled entirely in the python parser e.g. f'{hello=}' is actually parsed as if it was f'hello={hello!r}'. python-minifier currently doesn't make any attempt to recognise this and use the shorter form, so can easily end up with the output being longer than the input. This transform is a good idea, but it might not be very effective right now because of this.

ArztKlein commented 1 year ago

So it'd need some odd check to see if not renamining the variable would be shorter which seems incredibly unlikely. It also appears that if that were to happen, the only use of the variable would be concatenated inside of the string which means having the variable in the first place is useless in the minified version

dflook commented 1 year ago

Version 2.9.0 has been released which tries to use f-string debug specifiers where it can. Generally this means f'my_var={my_var!r}' is minified to f'{my_var=}'. Any typical use of the debug specifier in the input source will probably be preserved, but it will give up with particularly complex f-strings for performance reasons.