
On Wed, Mar 02, 2022 at 09:25:01AM -0500, Ricky Teachey wrote:
Is there some opportunity for some kind of compiler magic when the iterable of a for loop is fully contained in a place easily findable by the compiler, and not spread over multiple if and for statements?
I am not an expert on compiler optimization techniques, but I would be very surprised if something as minor as a computation being split over two statements instead of one would make a difference. What would make a difference would be statements *between* the for and the if: # some hypothetical optimization may apply for spam in eggs: if cheese: block # may block the optimization for spam in eggs: block if cheese: block but even there, a *sufficiently smart* optimizer may be able to do some pretty wild things. This is why, for instance, optimizing C compilers can often completely reorder your code. https://stackoverflow.com/questions/26190364/is-it-legal-for-a-c-optimizer-t... In a practical sense, given the relatively limited human and financial resources available to Python compared to C, it might be slightly easier for *people* to program an optimizer to spot the opportunity in the single statement case compared to the two statement case. But even there, I doubt it -- optimization is unlikely to occur at the source code level, more likely at the AST or even bytecode level, where any such difference between 1 vs 2 statements is likely to disappear. -- Steve