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