ยปCore Development>Code coverage>Lib/rlcompleter.py

Python code coverage for Lib/rlcompleter.py

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