Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Add tests for str subclasses
  • Loading branch information
mhsmith committed Apr 27, 2024
commit 3014e6c375a81dd4fc809d1e5efe64c31f8ea446
4 changes: 4 additions & 0 deletions Lib/_android_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ def write(self, s):
raise TypeError(
f"write() argument must be str, not {type(s).__name__}")

# In case `s` is a str subclass that writes itself to stdout or stderr
# when we call its methods, convert it to an actual str.
s = str.__str__(s)

# We want to emit one log message per line wherever possible, so split
# the string before sending it to the superclass. Note that
# "".splitlines() == [], so nothing will be logged for an empty string.
Expand Down
10 changes: 10 additions & 0 deletions Lib/test/test_android.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,16 @@ def write(s, lines=None):
write("hello\r\nworld\r\n", ["hello", "world"])
write("\r\n", [""])

# String subclasses are accepted, and if their methods write
# themselves, this doesn't cause infinite recursion.
class CustomStr(str):
def splitlines(self, *args, **kwargs):
sys.stdout.write(self)
return super().splitlines(*args, **kwargs)
Comment thread
serhiy-storchaka marked this conversation as resolved.
Outdated

write(CustomStr("custom\n"), ["custom"])

# Non-string classes are not accepted.
for obj in [b"", b"hello", None, 42]:
with self.subTest(obj=obj):
with self.assertRaisesRegex(
Expand Down