Issue 10649: Attempting to override special methods of a function object does not cause an error (original) (raw)

Attempting to override a special method of an object of a builtin (like list) raises an AttributeError. This is obviously by design. However, doing the same to a user-defined function object seemingly replaces the function, but does not have the expected effect. In the interests of consistency, attempting to change a special method of a function object should raise an AttributeError stating that the property/method is read-only.

a_list = list() a_list.repr = lambda: '[]' Traceback (most recent call last): File "", line 1, in AttributeError: 'list' object attribute 'repr' is read-only

def f(): pass f.repr = lambda: 'f' f.repr <function at 0x6482b0> repr(f) #would expect it to return 'f' since no error was raised '<function f at 0x6481f0>' f.repr() #so the change is half-way made, inconsistent and possibly problematic 'f'

As you observe, the attribute is not read only, it simply isn't referred to when special method lookup is done. This is specified as part of the language design for new style classes, but has only been made consistently true in recent versions.

On on the other hand, the special methods are not special in regard to their read-only nature on builtin types:

l = list() l.append = '1' Traceback (most recent call last): File "", line 1, in AttributeError: 'list' object attribute 'append' is read-only

Thus, this is not a bug, it's just the way the language works.