Can I modify the behavior of any dunder method of any class? For example, can I modify the behavior of the __add__
method of the str
class? (Totally illogical, but I just want to know if the language is protected from accidental overrides or not.)
Asked
Active
Viewed 440 times
-1
-
Python does support `super` class inheritance. So, it should work. Hopefully. Just make sure it doesn't affect any other functions – A random coder Jan 29 '21 at 13:13
-
You could create a subclass of `str` and alter its behaviour with respect to `__add__`, but it would only affect instances of your subclass, not normal strings. – khelwood Jan 29 '21 at 13:17
1 Answers
3
You can monkey-patch a lot, but not anything that's implemented in C, which includes the built-in str
class.
>>> str.__add__ = lambda x, y: 'xyzzy'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'str'
Similarly, you can't override __add__
on collections.defaultdict
:
>>> from collections import defaultdict
>>> defaultdict.__add__ = lambda x, y: 'xyzzy'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'collections.defaultdict'
Once you get away from the very core, though, you can often override things, even in the standard library:
>>> from random import Random
>>> Random.__add__ = lambda x, y: 'xyzzy'
>>> Random() + Random()
'xyzzy'
You still can't override things that are implemented in C, even if they're third-party libraries:
>>> import numpy as np
>>> np.ndarray.__add__ = lambda x, y: 'xyzzy'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'numpy.ndarray'

Jiří Baum
- 6,697
- 2
- 17
- 17
-
PS: looks like there actually is a library for monkey-patching built-in types: [forbiddenfruit](https://pypi.org/project/forbiddenfruit/); never tried it, though – Jiří Baum Jul 14 '22 at 14:44