Applicability of __debug__ for console_scripts

I’m interested in any route(s) to making the -O argument, and thus the __debug__ builtin, useful in console scripts. On some systems, you can manually change the shebang in the executable written during installation to #!python -O to turn off __debug__. How could that be automated?

I see that a prior discussion (23842) on interpreter options led @jack1142 to mention the -O argument (and not for the first time, apparently ;). The action suggested was to see if any of the “wheel installers” would consider. Sorry for my ignorance, but who is that? Is pip a wheel installer? Is hatchling/setuptools/flit/pdm a wheel installer?

Is there any alternative to modifying the shebang? My understanding is that the -O flag influences the import mechanism to create or use __pycache__ files with the .opt-1.pyc extension. Sorry (again) if this is way off base, but can the import mechanism be configured after startup to create or use .opt-1.pyc files? My idea here is whether the executable itself can configure the import of the callable specified as the entry point.

Yes, they all are. Any tool that installs Python packages would be a “wheel installer”.

Correct, ignoring the dropping of assert statements and __debug__ to False.

With some effort, yes. You would have to swap out all the import-related parts with finders that returned loaders that only loaded opt-1.pyc files. You may want to also set it up so you write out the .opt-1.pyc files.

The sys module has the places to update and importlib has the code to help you. But I will say it’s a lot of state to update and it can be easy to miss something.

Note that the -O option doesn’t achieve much. You should measure if it gives you any practical benefit (chances are it doesn’t) before trying to enable it in your build chain.