-
Notifications
You must be signed in to change notification settings - Fork 10
/
io_utils.py
71 lines (57 loc) · 2.18 KB
/
io_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import codecs
import io
from typing import IO
# notes:
# - For streams and modes see 'io.open()'
# - Stream classes have a pretty strange 'typing'/ABC/inheritance/etc arrangement because,
# among others, they are implemented in C.
# - Use `IO[X]` for arguments and `TextIO`/`BinaryIO` for return types (says GVR).
# https://github.com/python/typing/issues/518#issuecomment-350903120
def with_mode_binary(stream: IO) -> bool:
"""
Return whether ``stream`` is a binary stream (i.e. reads bytes).
"""
result = False
try:
result = 'b' in stream.mode
except AttributeError:
if isinstance(stream, (io.RawIOBase, io.BufferedIOBase, io.BytesIO)):
result = True
return result
def with_mode_text(stream: IO) -> bool:
"""
Return whether ``stream`` is a text stream (i.e. reads strings).
"""
result = False
try:
result = 't' in stream.mode
except AttributeError:
if isinstance(stream, (io.TextIOBase, io.TextIOWrapper, io.StringIO)):
result = True
return result
def with_encoding_utf8(text_stream: IO[str]) -> bool:
"""
Return whether ``text_stream`` is a text stream with encoding set to UTF-8.
:raises TypeError: if ``text_stream`` is not a text stream
"""
result = False
if isinstance(text_stream, io.StringIO):
# note: 'StringIO' saves (unicode) strings in memory and therefore doesn't have (or need)
# an encoding, which is fine.
# https://stackoverflow.com/questions/9368865/io-stringio-encoding-in-python3/9368909#9368909
result = True
else:
try:
text_stream_encoding: str = text_stream.encoding # type: ignore
except AttributeError as exc:
raise TypeError("Value is not a text stream.") from exc
if text_stream_encoding is None:
# e.g. the strange case of `tempfile.SpooledTemporaryFile(mode='rt', encoding='utf-8')`
pass
else:
try:
text_stream_encoding_norm = codecs.lookup(text_stream_encoding).name
result = text_stream_encoding_norm == 'utf-8'
except LookupError:
pass
return result