

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Pure Functions
incomplete
2: Pure Function Review
incomplete
3: Reference vs. Value
incomplete
4: Pass by Reference Impurity
incomplete
5: Input and Output
incomplete
6: Should I I/O?
incomplete
7: No-Op
incomplete
8: Memoization
incomplete
9: Referential Transparency
incomplete
10: Pure Functions Practice
incomplete
11: Pure Functions Practice
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
When you pass a value into a function as an argument, one of two things can happen:
There is more nuance to it, but this explanation works for an introduction. In Python, the following types are passed by reference:
These types, on the other hand, are passed by value:
Most container types are passed by reference (except for tuples!), and most basic types are passed by value.
Lists are passed by reference and are mutable:
def modify_list(inner_lst: list[int]) -> None:
inner_lst.append(4)
# the original "outer_lst" is updated
# because inner_lst is a reference to the original
outer_lst: list[int] = [1, 2, 3]
modify_list(outer_lst)
# outer_lst = [1, 2, 3, 4]
Integers are passed by value; they can be copied freely but are immutable:
def attempt_to_modify(inner_num: int) -> None:
inner_num += 1
# the original "outer_num" is not updated
# because inner_num is a copy of the original
outer_num: int = 1
attempt_to_modify(outer_num)
# outer_num = 1
We have a way for Doc2Doc users to set their supported formats in their settings. In memory, we store those settings as a simple dictionary:
settings: dict[str, bool] = {"docx": True, "pdf": True, "txt": False}
Unfortunately, there's a bug in our code. When a new format is added or removed, it not only updates the new dictionary, but it changes the defaults themselves! That's not good. We want to create a new dictionary with the updates, not change the original.
Fix the bug by making add_format and remove_format pure functions that don't mutate their inputs.
Simply assigning a new variable to an existing dictionary doesn't copy that dictionary; it points to the same dictionary. Instead, use the .copy() method to create a new copy of a dictionary.