Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions python315-utf8-default/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Python 3.15 Preview: UTF-8 by Default

This folder provides the code examples for the Real Python tutorial [Python 3.15 Preview: UTF-8 by Default](https://realpython.com/python315-utf8-default/)
6 changes: 6 additions & 0 deletions python315-utf8-default/app_v1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import json

with open("data.json") as f:
data = json.load(f)

print(f"Loaded {len(data)} entries")
6 changes: 6 additions & 0 deletions python315-utf8-default/app_v2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from constants import ENCODING

with open("data.json", encoding=ENCODING) as f:
data = f.read()

print(f"Loaded {len(data)} entries")
1 change: 1 addition & 0 deletions python315-utf8-default/constants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ENCODING = "utf-8" # Single source of truth for text I/O
5 changes: 5 additions & 0 deletions python315-utf8-default/explicit_encoding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
with open("data.json", encoding="utf-8") as f: # Portable and unambiguous
data = f.read()

with open("legacy.csv", encoding="locale") as f: # Intentional locale use
legacy = f.read()
2 changes: 2 additions & 0 deletions python315-utf8-default/locale_encoding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
with open("legacy.csv", encoding="locale") as f:
legacy = f.read()
3 changes: 3 additions & 0 deletions python315-utf8-default/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import textlib

textlib.read_text("notes.txt")
3 changes: 3 additions & 0 deletions python315-utf8-default/os_encoding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import locale

print(locale.getencoding()) # The real OS encoding, ignores UTF-8 Mode
7 changes: 7 additions & 0 deletions python315-utf8-default/textlib.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import io


def read_text(path, encoding=None):
encoding = io.text_encoding(encoding) # Points at the caller
with open(path, encoding=encoding) as f:
return f.read()
Loading