No, Python cannot make assumptions about NOP; he cannot know at compile time what type of string object is, and that he will remain that type throughout the entire program run.
There are several optimizations during compilation, mainly in the peephole optimizer . It does things like:
Replace list and set literals used in the membership test with immutable equivalents; this only works if the literal object is not assigned, it is used only in comparison; eg:.
if foo in ['spam', 'ham', 'eggs']:
replaced by
if foo in ('spam', 'ham', 'eggs'):
Replace simple calculations with the result:
one_week = 7 * 24 * 60 * 60
replaced by
one_week = 604800
This also happens for sequences; 'neener' * 3 is replaced by the result of this multiplication if the resulting sequence remains within 21 elements.
These optimizations are possible only because they are associated with immutable literal values; constant values ββthat are completely under the control of the interpreter, and you can rely on them to not switch types halfway through execution.
source share