Replaces the cache dict in the standard-library linecache module, to also remember (in an unerasable way) bpython console input.
| 3 | |
| 4 | |
| 5 | class BPythonLinecache(dict): |
| 6 | """Replaces the cache dict in the standard-library linecache module, |
| 7 | to also remember (in an unerasable way) bpython console input.""" |
| 8 | |
| 9 | def __init__( |
| 10 | self, |
| 11 | bpython_history: None | (list[tuple[int, None, list[str], str]]) = None, |
| 12 | *args, |
| 13 | **kwargs, |
| 14 | ) -> None: |
| 15 | super().__init__(*args, **kwargs) |
| 16 | self.bpython_history = bpython_history or [] |
| 17 | |
| 18 | def is_bpython_filename(self, fname: Any) -> bool: |
| 19 | return isinstance(fname, str) and fname.startswith("<bpython-input-") |
| 20 | |
| 21 | def get_bpython_history(self, key: str) -> tuple[int, None, list[str], str]: |
| 22 | """Given a filename provided by remember_bpython_input, |
| 23 | returns the associated source string.""" |
| 24 | try: |
| 25 | idx = int(key.split("-")[2][:-1]) |
| 26 | return self.bpython_history[idx] |
| 27 | except (IndexError, ValueError): |
| 28 | raise KeyError |
| 29 | |
| 30 | def remember_bpython_input(self, source: str) -> str: |
| 31 | """Remembers a string of source code, and returns |
| 32 | a fake filename to use to retrieve it later.""" |
| 33 | filename = f"<bpython-input-{len(self.bpython_history)}>" |
| 34 | self.bpython_history.append( |
| 35 | (len(source), None, source.splitlines(True), filename) |
| 36 | ) |
| 37 | return filename |
| 38 | |
| 39 | def __getitem__(self, key: Any) -> Any: |
| 40 | if self.is_bpython_filename(key): |
| 41 | return self.get_bpython_history(key) |
| 42 | return super().__getitem__(key) |
| 43 | |
| 44 | def __contains__(self, key: Any) -> bool: |
| 45 | if self.is_bpython_filename(key): |
| 46 | try: |
| 47 | self.get_bpython_history(key) |
| 48 | return True |
| 49 | except KeyError: |
| 50 | return False |
| 51 | return super().__contains__(key) |
| 52 | |
| 53 | def __delitem__(self, key: Any) -> None: |
| 54 | if not self.is_bpython_filename(key): |
| 55 | super().__delitem__(key) |
| 56 | |
| 57 | |
| 58 | def _bpython_clear_linecache() -> None: |
no outgoing calls
no test coverage detected