1
0
mirror of https://github.com/jbranchaud/til synced 2026-03-03 22:48:45 +00:00

Add Load A File Into The Python REPL as a Python TIL

This commit is contained in:
jbranchaud
2026-02-21 16:58:57 -06:00
parent d084e0ffe0
commit df418b5718
2 changed files with 37 additions and 1 deletions

View File

@@ -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).
_1741 TILs and counting..._
_1742 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
- [Dunder Methods](python/dunder-methods.md)
- [Install With PIP For Specific Interpreter](python/install-with-pip-for-specific-interpreter.md)
- [Iterate First N Items From Enumerable](python/iterate-first-n-items-from-enumerable.md)
- [Load A File Into The Python REPL](python/load-a-file-into-the-python-repl.md)
- [Override The Boolean Context Of A Class](python/override-the-boolean-context-of-a-class.md)
- [Store And Access Immutable Data In A Tuple](python/store-and-access-immutable-data-in-a-tuple.md)
- [Test A Function With Pytest](python/test-a-function-with-pytest.md)

View File

@@ -0,0 +1,35 @@
# Load A File Into The Python REPL
I opened up a Python REPL to try some things out.
```
$ python3
>>> import math
>>> math.floor(5/2)
2
```
Now, I want to reference a Python file I've been working on so that I can
manually test the behavior of what I'm building. To do this, I can import a file
by its name in the same way that I would import any module. Then I can use that
namespace for class and method references. Crucially, the file should exist in
the same directory the REPL was started from.
First, here is the file:
```python
# bpe.py
class BytePairEncoding:
def text_to_bytes(text: str) -> list[int]:
"""Convert a string to a list of byte values (0-255)"""
return list(text.encode("utf-8"))
```
Now to use it from the REPL:
```
$ python
>>> import bpe
>>> bpe.BytePairEncoding.text_to_bytes("Gimme some bytes!")
[71, 105, 109, 109, 101, 32, 115, 111, 109, 101, 32, 98, 121, 116, 101, 115, 33]
```