Which of the following built-in types are mutable, and which of them are immutable? And why?
- function (in particular, method)
- user-defined class
- class instance
- module
- file type (for example,
_io.TextIOWrapper
)
The official reference says the following here:
Unlike function objects, code objects are immutable and contain no references (directly or indirectly) to mutable objects.
I think this implies that functions are mutable because function objects can contain references (directly or indirectly) to mutable objects. Also it is always possible to change the code of a function object without affecting its id (see example here).
Next, one of the most upvoted answers on the topic of mutability claims that user-defined class and class instance are mutable types. Unfortunately, it doesn’t explain why.
1