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