Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/IPython/utils/dir2.py: 18%
34 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
1# encoding: utf-8
2"""A fancy version of Python's builtin :func:`dir` function.
3"""
5# Copyright (c) IPython Development Team.
6# Distributed under the terms of the Modified BSD License.
8import inspect
9import types
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
23def dir2(obj):
24 """dir2(obj) -> list of strings
26 Extended version of the Python builtin dir(), which does a few extra
27 checks.
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 """
35 # Start building the attribute list via dir(), and then complete it
36 # with a few extra special-purpose calls.
38 try:
39 words = set(dir(obj))
40 except Exception:
41 # TypeError: dir(obj) does not return a list
42 words = set()
44 if safe_hasattr(obj, '__class__'):
45 words |= set(dir(obj.__class__))
47 # filter out non-string attributes which may be stuffed by dir() calls
48 # and poor coding in third-party modules
50 words = [w for w in words if isinstance(w, str)]
51 return sorted(words)
54def get_real_method(obj, name):
55 """Like getattr, but with a few extra sanity checks:
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
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
69 if canary is not None:
70 # It claimed to have an attribute it should never have
71 return None
73 try:
74 m = getattr(obj, name, None)
75 except Exception:
76 return None
78 if inspect.isclass(obj) and not isinstance(m, types.MethodType):
79 return None
81 if callable(m):
82 return m
84 return None