-1

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.)

2
  • Python does support super class inheritance. So, it should work. Hopefully. Just make sure it doesn't affect any other functions Commented Jan 29, 2021 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. Commented Jan 29, 2021 at 13:17

1 Answer 1

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'
Sign up to request clarification or add additional context in comments.

1 Comment

PS: looks like there actually is a library for monkey-patching built-in types: forbiddenfruit; never tried it, though

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.