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