GH-128520: pathlib ABCs: raise text encoding warnings at correct stack level (#133051)

Ensure that warnings about unspecified text encodings are emitted from
`ReadablePath.read_text()`, `WritablePath.write_text()` and `magic_open()`
with the correct stack level set.
This commit is contained in:
Barney Gale 2025-04-28 19:04:20 +01:00 committed by GitHub
parent 6f04325992
commit fbffd70328
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 59 additions and 4 deletions

View file

@ -12,6 +12,7 @@
from abc import ABC, abstractmethod
from glob import _PathGlobber
from io import text_encoding
from pathlib._os import magic_open, ensure_distinct_paths, ensure_different_files, copyfileobj
from pathlib import PurePath, Path
from typing import Optional, Protocol, runtime_checkable
@ -262,6 +263,9 @@ def read_text(self, encoding=None, errors=None, newline=None):
"""
Open the file in text mode, read it, and close the file.
"""
# Call io.text_encoding() here to ensure any warning is raised at an
# appropriate stack level.
encoding = text_encoding(encoding)
with magic_open(self, mode='r', encoding=encoding, errors=errors, newline=newline) as f:
return f.read()
@ -391,6 +395,9 @@ def write_text(self, data, encoding=None, errors=None, newline=None):
"""
Open the file in text mode, write to it, and close the file.
"""
# Call io.text_encoding() here to ensure any warning is raised at an
# appropriate stack level.
encoding = text_encoding(encoding)
if not isinstance(data, str):
raise TypeError('data must be str, not %s' %
data.__class__.__name__)