I discovered today that Python’s True
and False
are actually constants—which means that their values can be changed. While this has been disallowed in Python 3, it still allows you to wreak some havoc in your—or someone else’s—Python 2 programs.
Definitely don’t do this
I wrote a tiny module that, when imported, will reverse your boolean values for the entirety of that Python instance—not just that namespace.
# destroybooleans.py
# For some reason, in Python 2.x True and False are both constants--meaning that
# they can have new values assigned to them.
# This malicious script exploits that. Upon import, will reverse
# True and False for all modules in the current Python environment.
# This obviously can have serious consequences.
import sys
# If we reverse them by still using the `bool` type, checking if type(False)==bool
# won't help us catch this
sys.modules['__builtin__'].True = bool(0)
sys.modules['__builtin__'].False = bool(1)
def __modules():
return sys.modules
def faux_method():
print "I did some nasty stuff on my way into your runtime >:D"
faux_method()
This obviously could be maliciously hidden in a larger package meant to have other functionality in order to mess up your code. I imagine that it would be difficult to notice in part due to Python’s otherwise very convenient truthiness and falsiness behavior. This module does not affect []
and {}
, for example, being false-y, nor does it prevent most objects from being truthy. This would only affect explicit calls to True
and False
.
This leads to some rather odd behavior:
>>> import destroybooleans
I did some nasty stuff on my way into your runtime >:D
>>> True
False
>>> False
True
>>> bool(1)
True
>>> bool([])
False