Last active
August 25, 2025 19:33
-
-
Save jakekara/26f1b54b556debf1a7c374d772077d2e to your computer and use it in GitHub Desktop.
Demo showing that Python modifies objects in place
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Demonstrate how Python modifies values by reference, so if you pass an objec to | |
| a function and modify it, it's modified even outside of the scope of that function, | |
| so there is no need to return the modified object. | |
| When you run this you should see something like: | |
| 139706416086160 Default description | |
| 139706416086160 Nothing very interesting. Le sigh. | |
| """ | |
| from dataclasses import dataclass | |
| @dataclass | |
| class InventoryItem: | |
| name: str | |
| description: str = "Default description" | |
| def modify_description(some_inventory_item: InventoryItem): | |
| some_inventory_item.description = "Nothing very interesting. Le sigh." | |
| notebook = InventoryItem(name="Notebook") | |
| # Print the notebook description, then call modify_description, and print the | |
| # description one more time. This demonstrates the object is modified in place | |
| # Print the id of the object to prove we're looking at the same object both times | |
| print(id(notebook), notebook.description) | |
| modify_description(notebook) | |
| print(id(notebook), notebook.description) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment