In functional programming, immutability and pure functions are core concepts that lead to safer, easier-to-debug code. Python, while multi-paradigm, allows you to leverage these concepts to write robust applications.
Mutable vs. Immutable
An immutable object involves state that cannot be modified after it is created. In Python, strings, tuples, and integers are immutable. Lists, dictionaries, and most custom objects are mutable.
The Dangers of Argument Mutation
Modifying mutable arguments (like lists or dicts) inside a function creates side effects. This can lead to bugs where data is changed unexpectedly elsewhere in your program.
Writing Pure Functions
A pure function has two properties:
- It always returns the same output for the same input.
- It has no side effects (it doesn't modify external state or arguments).
To fix the previous example, create a new list instead of modifying the old one:
Frozen Dataclasses
When defining your own data structures, you can enforce immutability using the frozen=True parameter in standard library dataclasses.
By treating data as immutable, you eliminate an entire class of bugs related to shared mutable state.