##// END OF EJS Templates
Merge pull request #10046 from ivanov/fix-tab-completion...
Matthias Bussonnier -
r23444:3c154253 merge
parent child Browse files
Show More
@@ -1,80 +1,83 b''
1 1 # encoding: utf-8
2 2 """A fancy version of Python's builtin :func:`dir` function.
3 3 """
4 4
5 5 # Copyright (c) IPython Development Team.
6 6 # Distributed under the terms of the Modified BSD License.
7 7
8 8 import inspect
9 9
10 10
11 11 def safe_hasattr(obj, attr):
12 12 """In recent versions of Python, hasattr() only catches AttributeError.
13 13 This catches all errors.
14 14 """
15 15 try:
16 16 getattr(obj, attr)
17 17 return True
18 18 except:
19 19 return False
20 20
21 21
22 22 def dir2(obj):
23 23 """dir2(obj) -> list of strings
24 24
25 25 Extended version of the Python builtin dir(), which does a few extra
26 26 checks.
27 27
28 28 This version is guaranteed to return only a list of true strings, whereas
29 29 dir() returns anything that objects inject into themselves, even if they
30 30 are later not really valid for attribute access (many extension libraries
31 31 have such bugs).
32 32 """
33 33
34 34 # Start building the attribute list via dir(), and then complete it
35 35 # with a few extra special-purpose calls.
36 36
37 37 try:
38 38 words = set(dir(obj))
39 39 except Exception:
40 40 # TypeError: dir(obj) does not return a list
41 41 words = set()
42 42
43 if safe_hasattr(obj, '__class__'):
44 words |= set(dir(obj.__class__))
45
43 46 # filter out non-string attributes which may be stuffed by dir() calls
44 47 # and poor coding in third-party modules
45 48
46 49 words = [w for w in words if isinstance(w, str)]
47 50 return sorted(words)
48 51
49 52
50 53 def get_real_method(obj, name):
51 54 """Like getattr, but with a few extra sanity checks:
52 55
53 56 - If obj is a class, ignore its methods
54 57 - Check if obj is a proxy that claims to have all attributes
55 58 - Catch attribute access failing with any exception
56 59 - Check that the attribute is a callable object
57 60
58 61 Returns the method or None.
59 62 """
60 63 if inspect.isclass(obj):
61 64 return None
62 65
63 66 try:
64 67 canary = getattr(obj, '_ipython_canary_method_should_not_exist_', None)
65 68 except Exception:
66 69 return None
67 70
68 71 if canary is not None:
69 72 # It claimed to have an attribute it should never have
70 73 return None
71 74
72 75 try:
73 76 m = getattr(obj, name, None)
74 77 except Exception:
75 78 return None
76 79
77 80 if callable(m):
78 81 return m
79 82
80 83 return None
General Comments 0
You need to be logged in to leave comments. Login now