diff --git a/python315-utf8-default/README.md b/python315-utf8-default/README.md new file mode 100644 index 0000000000..ff4e56e470 --- /dev/null +++ b/python315-utf8-default/README.md @@ -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/) diff --git a/python315-utf8-default/app_v1.py b/python315-utf8-default/app_v1.py new file mode 100644 index 0000000000..293e7c5191 --- /dev/null +++ b/python315-utf8-default/app_v1.py @@ -0,0 +1,6 @@ +import json + +with open("data.json") as f: + data = json.load(f) + +print(f"Loaded {len(data)} entries") diff --git a/python315-utf8-default/app_v2.py b/python315-utf8-default/app_v2.py new file mode 100644 index 0000000000..cd8f8c3b62 --- /dev/null +++ b/python315-utf8-default/app_v2.py @@ -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") diff --git a/python315-utf8-default/constants.py b/python315-utf8-default/constants.py new file mode 100644 index 0000000000..008e45dad7 --- /dev/null +++ b/python315-utf8-default/constants.py @@ -0,0 +1 @@ +ENCODING = "utf-8" # Single source of truth for text I/O diff --git a/python315-utf8-default/explicit_encoding.py b/python315-utf8-default/explicit_encoding.py new file mode 100644 index 0000000000..62d8e79ae4 --- /dev/null +++ b/python315-utf8-default/explicit_encoding.py @@ -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() diff --git a/python315-utf8-default/locale_encoding.py b/python315-utf8-default/locale_encoding.py new file mode 100644 index 0000000000..b575dce912 --- /dev/null +++ b/python315-utf8-default/locale_encoding.py @@ -0,0 +1,2 @@ +with open("legacy.csv", encoding="locale") as f: + legacy = f.read() diff --git a/python315-utf8-default/main.py b/python315-utf8-default/main.py new file mode 100644 index 0000000000..9b3a62bb9a --- /dev/null +++ b/python315-utf8-default/main.py @@ -0,0 +1,3 @@ +import textlib + +textlib.read_text("notes.txt") diff --git a/python315-utf8-default/os_encoding.py b/python315-utf8-default/os_encoding.py new file mode 100644 index 0000000000..0038a4a521 --- /dev/null +++ b/python315-utf8-default/os_encoding.py @@ -0,0 +1,3 @@ +import locale + +print(locale.getencoding()) # The real OS encoding, ignores UTF-8 Mode diff --git a/python315-utf8-default/textlib.py b/python315-utf8-default/textlib.py new file mode 100644 index 0000000000..6a93c71bd1 --- /dev/null +++ b/python315-utf8-default/textlib.py @@ -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()