Archive
monkeypatching the string type
Problem
“A monkey patch is a way to extend or modify the run-time code of dynamic languages without altering the original source code.” (via wikipedia) That is, we have the standard library, and we want to add new features to it. For instance, in the stdlib a string cannot tell whether it is a palindrome or not, but we would like to extend the string type to support this feature:
>>> s = "racecar" >>> print(s.is_palindrome()) # Warning! It won't work. True
Is it possible in Python?
Solution
As pointed out in this thread, built-in types are implemented in C and you cannot modify them in runtime. As I heard Ruby allows this, but it doesn’t work in Python.
However, there is a workaround if you really want to do something like this. You can make a subclass of the built-in type and then you can extend it as you want. Example:
from __future__ import (absolute_import, division,
print_function, unicode_literals)
class MyStr(unicode):
"""
"monkeypatching" the unicode class
It's not real monkeypatching, just a workaround.
"""
def is_palindrome(self):
return self == self[::-1]
def main():
s = MyStr("radar")
print(s.is_palindrome())
####################
if __name__ == "__main__":
main()
