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