From 43ade88faba92eea9755ac66a2f26bf37900a0c8 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 24 Feb 2026 20:37:12 -0600 Subject: [PATCH] Add Access Most Recent Return Value In REPL as a Python TIL --- README.md | 3 +- ...access-most-recent-return-value-in-repl.md | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 python/access-most-recent-return-value-in-repl.md diff --git a/README.md b/README.md index 3c0dee2..86130eb 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ working across different projects via [VisualMode](https://www.visualmode.dev/). For a steady stream of TILs, [sign up for my newsletter](https://visualmode.kit.com/newsletter). -_1746 TILs and counting..._ +_1747 TILs and counting..._ See some of the other learning resources I work on: @@ -1038,6 +1038,7 @@ If you've learned something here, support my efforts writing daily TILs by ### Python - [Access Instance Variables](python/access-instance-variables.md) +- [Access Most Recent Return Value In REPL](python/access-most-recent-return-value-in-repl.md) - [Break Debugger On First Line Of Program](python/break-debugger-on-first-line-of-program.md) - [Check If Package Is Installed With Pip](python/check-if-package-is-installed-with-pip.md) - [Create A Dummy DataFrame In Pandas](python/create-a-dummy-dataframe-in-pandas.md) diff --git a/python/access-most-recent-return-value-in-repl.md b/python/access-most-recent-return-value-in-repl.md new file mode 100644 index 0000000..39f8a4c --- /dev/null +++ b/python/access-most-recent-return-value-in-repl.md @@ -0,0 +1,34 @@ +# Access Most Recent Return Value In REPL + +One of my favorite features of Ruby's `irb` and `pry` are that you can use `_` +to reference the most recent return value. Often as we use an interpreter or +REPL, we end up with _intermediate_ values. That is, we've execute some kind of +statement which returned a value and we now want to use that resulting value in +our next statement. Python also supports `_`. + +Let's say I've run a statement that took a while to process, but I forgot to +assign it to a variable. Instead of re-running the whole thing, I can create a +variable that references the previous return value using `_`. + +```python +>>> BytePairEncoding.train_bpe(long_text) +{'merge_rules': [...], 'vocab': {...}} +>>> result = _ +>>> list(result.keys()) +['merge_rules', 'vocab'] +``` + +Even if I don't necessarily want to assign it a variable, it can be nice to +reference the previous value as I continue with what I'm doing: + +```python +>>> result['merge_rules'][0][1] +256 +>>> result['vocab'][_] +b'e ' +``` + +Notice how the value from the first statement gets used as part of a `dict` +access. + +[source](https://docs.python.org/3/tutorial/introduction.html#numbers)