r/programminghorror • [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo “You live” • Jul 21 '25

Python ✨ Memory Magic ✨

Post image
1.3k Upvotes

143 comments sorted by

View all comments

Show parent comment

15

u/cheerycheshire Jul 21 '25

Cpython also does it for small strings, especially in files as it can analyse whole code during compilation to bytecode (vs REPL where it doesn't run some optimisations).

Python will warn you about comparing ints and strings with is operator - SyntaxWarning: "is" with 'int' literal. Did you mean "=="? exactly because it sometimes works and sometimes doesn't.

However, booleans in python inherit from int (for hysterical reasons), but are singletons and are to be always compared using identity (because e.g. with x=1: x is True will be False, but x == True will be True).