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