|
1 | 1 | import linecache |
2 | | -from typing import Any, List, Tuple |
| 2 | +from typing import Any, List, Tuple, Optional |
3 | 3 |
|
4 | 4 |
|
5 | 5 | class BPythonLinecache(dict): |
6 | 6 | """Replaces the cache dict in the standard-library linecache module, |
7 | 7 | to also remember (in an unerasable way) bpython console input.""" |
8 | 8 |
|
9 | | - def __init__(self, *args, **kwargs) -> None: |
| 9 | + def __init__( |
| 10 | + self, |
| 11 | + bpython_history: Optional[ |
| 12 | + List[Tuple[int, None, List[str], str]] |
| 13 | + ] = None, |
| 14 | + *args, |
| 15 | + **kwargs, |
| 16 | + ) -> None: |
10 | 17 | super().__init__(*args, **kwargs) |
11 | | - self.bpython_history: List[Tuple[int, None, List[str], str]] = [] |
| 18 | + self.bpython_history = bpython_history or [] |
12 | 19 |
|
13 | 20 | def is_bpython_filename(self, fname: Any) -> bool: |
14 | | - if isinstance(fname, str): |
15 | | - return fname.startswith("<bpython-input-") |
16 | | - else: |
17 | | - # In case the key isn't a string |
18 | | - return False |
| 21 | + return isinstance(fname, str) and fname.startswith("<bpython-input-") |
19 | 22 |
|
20 | 23 | def get_bpython_history(self, key: str) -> Tuple[int, None, List[str], str]: |
21 | 24 | """Given a filename provided by remember_bpython_input, |
@@ -58,14 +61,13 @@ def _bpython_clear_linecache() -> None: |
58 | 61 | if isinstance(linecache.cache, BPythonLinecache): |
59 | 62 | bpython_history = linecache.cache.bpython_history |
60 | 63 | else: |
61 | | - bpython_history = [] |
62 | | - linecache.cache = BPythonLinecache() |
63 | | - linecache.cache.bpython_history = bpython_history |
| 64 | + bpython_history = None |
| 65 | + linecache.cache = BPythonLinecache(bpython_history) |
64 | 66 |
|
65 | 67 |
|
66 | | -# Monkey-patch the linecache module so that we're able |
| 68 | +# Monkey-patch the linecache module so that we are able |
67 | 69 | # to hold our command history there and have it persist |
68 | | -linecache.cache = BPythonLinecache(linecache.cache) # type: ignore |
| 70 | +linecache.cache = BPythonLinecache(None, linecache.cache) # type: ignore |
69 | 71 | linecache.clearcache = _bpython_clear_linecache |
70 | 72 |
|
71 | 73 |
|
|
0 commit comments