
On 11/23/2022 3:02 PM, Chris Angelico wrote:
On Thu, 24 Nov 2022 at 06:46, Barry Scott<barry@barrys-emacs.org> wrote:
I have written a lot of low level protocol and IOCTL calls that cannot think of a time this would have helped me. struct is often a mean to create blocks of binary data.
Long strings of binary data would be a maintenance issue. What do all the bits mean? Sounds like a system of compile-time evaluation - as a way to extend constant folding to more forms - might be the way to do this, then. I don't think the compiler can optimize this:
x = bytes.fromhex("0123456789abcdef")
and while it's theoretically possible to optimize this, it falls down badly on the "why was this written like this?" test:
x = b"".fromhex("0123456789abcdef")
But suppose there were some way to say "this is intended to be a compile-time constant, please evaluate it and retain the result as a literal". Obviously this is only valid if the result is a type that can be saved, but it would allow some quite nice optimizations that might even include struct calls.
PEP 638 – Syntactic Macros would be perfect for this. It gives this example for f-strings: "The f-string |f"..."| could be implemented as macro as |f!("...")|. Not quite as nice to read, but would still be useful for experimenting with."
On the flip side, the performance gain probably wouldn't be all that much compared to doing the work at import time. For literals used in tight loops, there'd still be SOME benefit (if the work is done at import time, it would have to be stored as a global, and that means the inner loop is looking up a global rather than loading a constant), but it would have to be a fairly hot piece of code to be worth the effort.
That would be the beauty of 638: if it's important to one piece of code, it could be just enabled there. Of course the implementing macro would need to be either part of your application or become a dependency. But I'm under no delusions that this PEP will ever get accepted, unfortunately. Eric