forked frombpython/bpython
- Notifications
You must be signed in to change notification settings - Fork0
Expand file tree
/
Copy pathpatch_linecache.py
More file actions
83 lines (66 loc) · 2.78 KB
/
patch_linecache.py
File metadata and controls
83 lines (66 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# encoding: utf-8
from __future__importabsolute_import
importlinecache
classBPythonLinecache(dict):
"""Replaces the cache dict in the standard-library linecache module,
to also remember (in an unerasable way) bpython console input."""
def__init__(self,*args,**kwargs):
super(BPythonLinecache,self).__init__(*args,**kwargs)
self.bpython_history= []
defis_bpython_filename(self,fname):
try:
returnfname.startswith('<bpython-input-')
exceptAttributeError:
# In case the key isn't a string
returnFalse
defget_bpython_history(self,key):
"""Given a filename provided by remember_bpython_input,
returns the associated source string."""
try:
idx=int(key.split('-')[2][:-1])
returnself.bpython_history[idx]
except (IndexError,ValueError):
raiseKeyError
defremember_bpython_input(self,source):
"""Remembers a string of source code, and returns
a fake filename to use to retrieve it later."""
filename='<bpython-input-%s>'%len(self.bpython_history)
self.bpython_history.append((len(source),None,
source.splitlines(True),filename))
returnfilename
def__getitem__(self,key):
ifself.is_bpython_filename(key):
returnself.get_bpython_history(key)
returnsuper(BPythonLinecache,self).__getitem__(key)
def__contains__(self,key):
ifself.is_bpython_filename(key):
try:
self.get_bpython_history(key)
returnTrue
exceptKeyError:
returnFalse
returnsuper(BPythonLinecache,self).__contains__(key)
def__delitem__(self,key):
ifnotself.is_bpython_filename(key):
returnsuper(BPythonLinecache,self).__delitem__(key)
def_bpython_clear_linecache():
try:
bpython_history=linecache.cache.bpython_history
exceptAttributeError:
bpython_history= []
linecache.cache=BPythonLinecache()
linecache.cache.bpython_history=bpython_history
# Monkey-patch the linecache module so that we're able
# to hold our command history there and have it persist
linecache.cache=BPythonLinecache(linecache.cache)
linecache.clearcache=_bpython_clear_linecache
deffilename_for_console_input(code_string):
"""Remembers a string of source code, and returns
a fake filename to use to retrieve it later."""
try:
returnlinecache.cache.remember_bpython_input(code_string)
exceptAttributeError:
# If someone else has patched linecache.cache, better for code to
# simply be unavailable to inspect.getsource() than to raise
# an exception.
return'<input>'