Does anyone use `-O` or `-OO` or `PYTHONOPTIMIZE=1` in their deployments?

Yes to -O by default, no to -OO with a couple exceptions.

Why: Performance costs

Removing assertions mostly, tests run with -O.

I maintain typed code bases where assertions are used to inform the type checker of a type in a way that doesn’t involve a runtime cost where type-checking either can’t narrow (due to limitations of the type system) or where the means for it to would be more expensive. This pattern is only used where we invariantly know the assertion would pass, with no misuse of assertions for exceptions, and frequently with dependent types.

As for measurements, measurements prompted it, not the other way around.

assert isinstance(...) was showing up in profiling due to its presence in a tight loop. Given that -O only sets __debug__ to False and elides assertions, we’ve made no effort to continually measure for gains.

Removing -O would be seen as detrimental unless it was because it was the default behavior, especially if the situation where this was the only way to handle this case with static typing was still the case, however, that hasn’t really happened, and attempts at it were met with people saying “well, you shouldn’t need that” of “people don’t really use typing.cast” (see: Cast syntax for static typing), which at the time, I didn’t find worth getting into that with people, as the workable solution exists already with -O. We don’t use typing.cast because it has a runtime cost, assert isinstance doesn’t with -O, and the code isn’t public, so it isn’t going to show up in a code search on github. I’m sure other people have similar cases with finding that typing.cast is inferior to assert isinstance.

-OO is used in anything deployed to IoT for memory use reasons. In the cases I currently need to care about, we could probably drop one of the O’s there without it becoming problematic, but I don’t think this is true of all IoT uses of python.

4 Likes