It’s actually already possible to “curse” builtin types like str
:
>>> def mymethod(self):
... return self + " ook ook"
...
>>> def monkeypatch(type_, func):
... gc.get_referents(type_.__dict__)[0][func.__name__] = func
...
>>> import gc
>>> monkeypatch(str, mymethod)
>>> "hello".mymethod()
'hello ook ook'
Curse with an existing function:
>>> monkeypatch(str, textwrap.dedent)
>>> """
... hello
... world
... """.dedent()
'\nhello\nworld\n'
This is not a recommendation. It’s hackish, that’s an abuse of reference counting, and it probably only works in CPython.
If anyone asks, you didn’t hear it from me…