Extension methods in Python

It can be done with Forbidden Fruit (https://pypi.python.org/pypi/forbiddenfruit)

Install forbiddenfruit:

pip install forbiddenfruit

Then you can extend built-in types:

>>> from forbiddenfruit import curse

>>> def percent(self, delta):
...     return self * (1 + delta / 100)

>>> curse(float, 'percent', percent)
>>> 1.0.percent(5)
1.05

Forbidden Fruit is fundamentally dependent on the C API, it works only on cpython implementations and won’t work on other python implementations, such as Jython, pypy, etc.


You can add whatever methods you like on class objects defined in Python code (AKA monkey patching):

>>> class A(object):
>>>     pass


>>> def stuff(self):
>>>     print self

>>> A.test = stuff
>>> A().test()

This does not work on builtin types, because their __dict__ is not writable (it's a dictproxy).

So no, there is no "real" extension method mechanism in Python.