Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

rlcompleter.py 6.9 KB

You have to be logged in to leave a comment. Sign In
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
  1. """Word completion for GNU readline.
  2. The completer completes keywords, built-ins and globals in a selectable
  3. namespace (which defaults to __main__); when completing NAME.NAME..., it
  4. evaluates (!) the expression up to the last dot and completes its attributes.
  5. It's very cool to do "import sys" type "sys.", hit the completion key (twice),
  6. and see the list of names defined by the sys module!
  7. Tip: to use the tab key as the completion key, call
  8. readline.parse_and_bind("tab: complete")
  9. Notes:
  10. - Exceptions raised by the completer function are *ignored* (and generally cause
  11. the completion to fail). This is a feature -- since readline sets the tty
  12. device in raw (or cbreak) mode, printing a traceback wouldn't work well
  13. without some complicated hoopla to save, reset and restore the tty state.
  14. - The evaluation of the NAME.NAME... form may cause arbitrary application
  15. defined code to be executed if an object with a __getattr__ hook is found.
  16. Since it is the responsibility of the application (or the user) to enable this
  17. feature, I consider this an acceptable risk. More complicated expressions
  18. (e.g. function calls or indexing operations) are *not* evaluated.
  19. - When the original stdin is not a tty device, GNU readline is never
  20. used, and this module (and the readline module) are silently inactive.
  21. """
  22. import atexit
  23. import builtins
  24. import __main__
  25. __all__ = ["Completer"]
  26. class Completer:
  27. def __init__(self, namespace = None):
  28. """Create a new completer for the command line.
  29. Completer([namespace]) -> completer instance.
  30. If unspecified, the default namespace where completions are performed
  31. is __main__ (technically, __main__.__dict__). Namespaces should be
  32. given as dictionaries.
  33. Completer instances should be used as the completion mechanism of
  34. readline via the set_completer() call:
  35. readline.set_completer(Completer(my_namespace).complete)
  36. """
  37. if namespace and not isinstance(namespace, dict):
  38. raise TypeError('namespace must be a dictionary')
  39. # Don't bind to namespace quite yet, but flag whether the user wants a
  40. # specific namespace or to use __main__.__dict__. This will allow us
  41. # to bind to __main__.__dict__ at completion time, not now.
  42. if namespace is None:
  43. self.use_main_ns = 1
  44. else:
  45. self.use_main_ns = 0
  46. self.namespace = namespace
  47. def complete(self, text, state):
  48. """Return the next possible completion for 'text'.
  49. This is called successively with state == 0, 1, 2, ... until it
  50. returns None. The completion should begin with 'text'.
  51. """
  52. if self.use_main_ns:
  53. self.namespace = __main__.__dict__
  54. if not text.strip():
  55. if state == 0:
  56. if _readline_available:
  57. readline.insert_text('\t')
  58. readline.redisplay()
  59. return ''
  60. else:
  61. return '\t'
  62. else:
  63. return None
  64. if state == 0:
  65. if "." in text:
  66. self.matches = self.attr_matches(text)
  67. else:
  68. self.matches = self.global_matches(text)
  69. try:
  70. return self.matches[state]
  71. except IndexError:
  72. return None
  73. def _callable_postfix(self, val, word):
  74. if callable(val):
  75. word = word + "("
  76. return word
  77. def global_matches(self, text):
  78. """Compute matches when text is a simple name.
  79. Return a list of all keywords, built-in functions and names currently
  80. defined in self.namespace that match.
  81. """
  82. import keyword
  83. matches = []
  84. seen = {"__builtins__"}
  85. n = len(text)
  86. for word in keyword.kwlist:
  87. if word[:n] == text:
  88. seen.add(word)
  89. if word in {'finally', 'try'}:
  90. word = word + ':'
  91. elif word not in {'False', 'None', 'True',
  92. 'break', 'continue', 'pass',
  93. 'else'}:
  94. word = word + ' '
  95. matches.append(word)
  96. for nspace in [self.namespace, builtins.__dict__]:
  97. for word, val in nspace.items():
  98. if word[:n] == text and word not in seen:
  99. seen.add(word)
  100. matches.append(self._callable_postfix(val, word))
  101. return matches
  102. def attr_matches(self, text):
  103. """Compute matches when text contains a dot.
  104. Assuming the text is of the form NAME.NAME....[NAME], and is
  105. evaluable in self.namespace, it will be evaluated and its attributes
  106. (as revealed by dir()) are used as possible completions. (For class
  107. instances, class members are also considered.)
  108. WARNING: this can still invoke arbitrary C code, if an object
  109. with a __getattr__ hook is evaluated.
  110. """
  111. import re
  112. m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
  113. if not m:
  114. return []
  115. expr, attr = m.group(1, 3)
  116. try:
  117. thisobject = eval(expr, self.namespace)
  118. except Exception:
  119. return []
  120. # get the content of the object, except __builtins__
  121. words = set(dir(thisobject))
  122. words.discard("__builtins__")
  123. if hasattr(thisobject, '__class__'):
  124. words.add('__class__')
  125. words.update(get_class_members(thisobject.__class__))
  126. matches = []
  127. n = len(attr)
  128. if attr == '':
  129. noprefix = '_'
  130. elif attr == '_':
  131. noprefix = '__'
  132. else:
  133. noprefix = None
  134. while True:
  135. for word in words:
  136. if (word[:n] == attr and
  137. not (noprefix and word[:n+1] == noprefix)):
  138. match = "%s.%s" % (expr, word)
  139. try:
  140. val = getattr(thisobject, word)
  141. except Exception:
  142. pass # Include even if attribute not set
  143. else:
  144. match = self._callable_postfix(val, match)
  145. matches.append(match)
  146. if matches or not noprefix:
  147. break
  148. if noprefix == '_':
  149. noprefix = '__'
  150. else:
  151. noprefix = None
  152. matches.sort()
  153. return matches
  154. def get_class_members(klass):
  155. ret = dir(klass)
  156. if hasattr(klass,'__bases__'):
  157. for base in klass.__bases__:
  158. ret = ret + get_class_members(base)
  159. return ret
  160. try:
  161. import readline
  162. except ImportError:
  163. _readline_available = False
  164. else:
  165. readline.set_completer(Completer().complete)
  166. # Release references early at shutdown (the readline module's
  167. # contents are quasi-immortal, and the completer function holds a
  168. # reference to globals).
  169. atexit.register(lambda: readline.set_completer(None))
  170. _readline_available = True
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...