We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Pass by Reference Impurity

Because certain types in Python are passed by reference, we can mutate values that we didn't intend to. This is a form of function impurity!

Remember, a pure function has no side effects. It shouldn't modify anything outside of its scope, including its inputs. It should return new copies of inputs instead of changing them.

Pure Function

def remove_format(default_formats: dict[str, bool], old_format: str) -> dict[str, bool]:
    new_formats: dict[str, bool] = default_formats.copy()
    new_formats[old_format] = False
    return new_formats

Impure Function

def remove_format(default_formats: dict[str, bool], old_format: str) -> dict[str, bool]:
    default_formats[old_format] = False
    return default_formats

Why Do We Care?

One of the biggest differences between good and great developers is how often they incorporate pure functions into their code. Pure functions are easier to read, easier to reason about, easier to test, and easier to combine. Even if you're working in an imperative language like Python, you can (and should) write pure functions whenever reasonable.

There's nothing worse than trying to debug a program where the order of function calls needs to be juuuuust right because they all read and modify the same global variable.