According to python documentation assert statements aren’t included in code if it is compiled with -O key. I wondering if it is possible to emulate this behavior with any arbitrary piece of code?
For example, if I have a logger which is called heavily during execution I can benefit from eliminating if DEBUG: ... statements with all the code associated to them.
Since Python is an interpreted language, it can’t jump around in its own code. But you don’t need a “special tool” to strip off parts of your code — use Python for it!
Here is a minimal example. You’ll probably want to put the
strip_debug()function in your__init__.pyand let it process a list of modules. Also, you’d probably want to add some additional check that the user really wants to modify the code, not just run it. Probably, using a command line option like--purgewould be nice. You can then either make a copy of your library and once runbefore you publish the library or leave it up to your users to do so.
After executed, this file will only contain the functional code of the
foo()function. I have used the special commentsand
in this example which allows to strip off arbitrary code but if it’s just for removing
sections, it would also be pretty easy to detect those without any additional comments.