Text I/O implementation using an in-memory buffer. The initial_value argument sets the value of object. The newline argument is like the one of TextIOWrapper's constructor.
| 2662 | |
| 2663 | |
| 2664 | class StringIO(TextIOWrapper): |
| 2665 | """Text I/O implementation using an in-memory buffer. |
| 2666 | |
| 2667 | The initial_value argument sets the value of object. The newline |
| 2668 | argument is like the one of TextIOWrapper's constructor. |
| 2669 | """ |
| 2670 | |
| 2671 | def __init__(self, initial_value="", newline="\n"): |
| 2672 | super(StringIO, self).__init__(BytesIO(), |
| 2673 | encoding="utf-8", |
| 2674 | errors="surrogatepass", |
| 2675 | newline=newline) |
| 2676 | # Issue #5645: make universal newlines semantics the same as in the |
| 2677 | # C version, even under Windows. |
| 2678 | if newline is None: |
| 2679 | self._writetranslate = False |
| 2680 | if initial_value is not None: |
| 2681 | if not isinstance(initial_value, str): |
| 2682 | raise TypeError("initial_value must be str or None, not {0}" |
| 2683 | .format(type(initial_value).__name__)) |
| 2684 | self.write(initial_value) |
| 2685 | self.seek(0) |
| 2686 | |
| 2687 | def getvalue(self): |
| 2688 | self.flush() |
| 2689 | decoder = self._decoder or self._get_decoder() |
| 2690 | old_state = decoder.getstate() |
| 2691 | decoder.reset() |
| 2692 | try: |
| 2693 | return decoder.decode(self.buffer.getvalue(), final=True) |
| 2694 | finally: |
| 2695 | decoder.setstate(old_state) |
| 2696 | |
| 2697 | def __repr__(self): |
| 2698 | # TextIOWrapper tells the encoding in its repr. In StringIO, |
| 2699 | # that's an implementation detail. |
| 2700 | return object.__repr__(self) |
| 2701 | |
| 2702 | @property |
| 2703 | def errors(self): |
| 2704 | return None |
| 2705 | |
| 2706 | @property |
| 2707 | def encoding(self): |
| 2708 | return None |
| 2709 | |
| 2710 | def detach(self): |
| 2711 | # This doesn't make sense on StringIO. |
| 2712 | self._unsupported("detach") |
no outgoing calls