My safety check was an assert. Five lines made the module refuse to load without it.
assert isinstance(flag, bool) reads like a check. Under python -O it is not there at all, and nothing at the call site says so. The usual advice is to stop writing safety checks as asserts. There is a better answer: let the module refuse to be imported in the mode where its checks evaporate. if not __debug__ : raise RuntimeError ( " this module ' s checks are asserts; refusing to run with -O " )…
The safety check implemented by five lines of code in a module resolves the issue where the module would refuse to load when executed with the optimization flag -O. This safety measure ensures that the module cannot be imported in a mode where its checks are essentially ignored. By raising a RuntimeError, the module refuses to run when executed with -O, preventing any potential problems that might arise due to the safety checks being disabled.
This approach addresses two different questions: the question of which image the module was imported under, and the question of what process is running at the moment. The safety check leverages the sys.flags.optimize setting and the __debug__ variable to determine the correct behavior. By using this method, the module ensures that it is safe to run under -O and avoids any unexpected behavior or issues that may arise from relying solely on asserts.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.