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.
| 2704 | |
| 2705 | |
| 2706 | class StringIO(TextIOWrapper): |
| 2707 | """Text I/O implementation using an in-memory buffer. |
| 2708 | |
| 2709 | The initial_value argument sets the value of object. The newline |
| 2710 | argument is like the one of TextIOWrapper's constructor. |
| 2711 | """ |
| 2712 | |
| 2713 | def __init__(self, initial_value="", newline="\n"): |
| 2714 | super(StringIO, self).__init__(BytesIO(), |
| 2715 | encoding="utf-8", |
| 2716 | errors="surrogatepass", |
| 2717 | newline=newline) |
| 2718 | # Issue #5645: make universal newlines semantics the same as in the |
| 2719 | # C version, even under Windows. |
| 2720 | if newline is None: |
| 2721 | self._writetranslate = False |
| 2722 | if initial_value is not None: |
| 2723 | if not isinstance(initial_value, str): |
| 2724 | raise TypeError("initial_value must be str or None, not {0}" |
| 2725 | .format(type(initial_value).__name__)) |
| 2726 | self.write(initial_value) |
| 2727 | self.seek(0) |
| 2728 | |
| 2729 | def getvalue(self): |
| 2730 | self.flush() |
| 2731 | decoder = self._decoder or self._get_decoder() |
| 2732 | old_state = decoder.getstate() |
| 2733 | decoder.reset() |
| 2734 | try: |
| 2735 | return decoder.decode(self.buffer.getvalue(), final=True) |
| 2736 | finally: |
| 2737 | decoder.setstate(old_state) |
| 2738 | |
| 2739 | def __repr__(self): |
| 2740 | # TextIOWrapper tells the encoding in its repr. In StringIO, |
| 2741 | # that's an implementation detail. |
| 2742 | return object.__repr__(self) |
| 2743 | |
| 2744 | @property |
| 2745 | def errors(self): |
| 2746 | return None |
| 2747 | |
| 2748 | @property |
| 2749 | def encoding(self): |
| 2750 | return None |
| 2751 | |
| 2752 | def detach(self): |
| 2753 | # This doesn't make sense on StringIO. |
| 2754 | self._unsupported("detach") |
no outgoing calls