Text-ish stream wrapper that accepts both text and bytes in write(). Bytes are decoded using the file's (encoding, errors) before writing. Optionally approximates line-buffering by flushing when a newline is written.
| 332 | return any(ch in mode for ch in _WRITE_CHARS) |
| 333 | |
| 334 | class MixedWriteTextIO(object): |
| 335 | """ |
| 336 | Text-ish stream wrapper that accepts both text and bytes in write(). |
| 337 | Bytes are decoded using the file's (encoding, errors) before writing. |
| 338 | |
| 339 | Optionally approximates line-buffering by flushing when a newline is written. |
| 340 | """ |
| 341 | def __init__(self, fh, encoding, errors, line_buffered=False): |
| 342 | self._fh = fh |
| 343 | self._encoding = encoding |
| 344 | self._errors = errors |
| 345 | self._line_buffered = line_buffered |
| 346 | |
| 347 | def write(self, data): |
| 348 | # bytes-like but not text -> decode |
| 349 | if isinstance(data, _bytes_types) and not isinstance(data, _text_type): |
| 350 | data = bytes(data).decode(self._encoding, self._errors) |
| 351 | elif not isinstance(data, _text_type): |
| 352 | data = _text_type(data) |
| 353 | |
| 354 | n = self._fh.write(data) |
| 355 | |
| 356 | # Approximate "line buffering" behavior if requested |
| 357 | if self._line_buffered and u"\n" in data: |
| 358 | try: |
| 359 | self._fh.flush() |
| 360 | except Exception: |
| 361 | pass |
| 362 | |
| 363 | return n |
| 364 | |
| 365 | def writelines(self, lines): |
| 366 | for x in lines: |
| 367 | self.write(x) |
| 368 | |
| 369 | def __iter__(self): |
| 370 | return iter(self._fh) |
| 371 | |
| 372 | def __next__(self): |
| 373 | return next(self._fh) |
| 374 | |
| 375 | def next(self): # Py2 |
| 376 | return self.__next__() |
| 377 | |
| 378 | def __getattr__(self, name): |
| 379 | return getattr(self._fh, name) |
| 380 | |
| 381 | def __enter__(self): |
| 382 | self._fh.__enter__() |
| 383 | return self |
| 384 | |
| 385 | def __exit__(self, exc_type, exc, tb): |
| 386 | return self._fh.__exit__(exc_type, exc, tb) |
| 387 | |
| 388 | |
| 389 | def _codecs_open(filename, mode="r", encoding=None, errors="strict", buffering=-1): |
no outgoing calls
no test coverage detected
searching dependent graphs…