Why most of function attributions are writeable?

e.g.

>>> def foo(x, v=3):
...    print(x,v)
...
>>> foo.__defaults__
(3,)
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() missing 1 required positional argument: 'x'
>>> foo(2)
2 3
>>> foo.__defaults__="x",6
>>> foo.__defaults__
('x', 6)
>>> foo()
x 6

It means there is a chance to modify the function contract during runtime. But would that causes surprise when most of users anticipate a function’s behavior per reading its definition(contract)?
Someone may argue that increases the flexibility, though I doubt if increasing flexibility is always a positive thing to take.

And is there any specific use cases demand function attributions being writeable?

Consenting adults. This sort of dynamic programming is incredibly useful, and what would be gained by locking it down?

Oh yes, lots. Quite a few handy function decorators work, not by constructing an inefficient run-time wrapper, but by modifying the existing function.

1 Like

To the very specific question about whether it’s modifiable:

says that __defaults__ is writable, so yes - allowed. I’ve never found a need to modify __defaults__ myself, nor have I ever seen it in code, and it feels kind of odd to do so, but other attributes at runtime - absolutely.