Skip to content

Commit 3ad203d

Browse files
committed
Implement ContextManager for AttrCleaner
Also extend some documentation.
1 parent fb923fd commit 3ad203d

File tree

2 files changed

+9
-6
lines changed

2 files changed

+9
-6
lines changed

bpython/autocomplete.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -458,8 +458,9 @@ def attr_lookup(self, obj: Any, expr: str, attr: str) -> List:
458458
return matches
459459

460460
def list_attributes(self, obj: Any) -> List[str]:
461-
# TODO: re-implement dir using getattr_static to avoid using
462-
# AttrCleaner here?
461+
# TODO: re-implement dir without AttrCleaner here
462+
#
463+
# Note: accessing `obj.__dir__` via `getattr_static` is not side-effect free.
463464
with inspection.AttrCleaner(obj):
464465
return dir(obj)
465466

bpython/inspection.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
import pydoc
2727
import re
2828
from dataclasses import dataclass
29-
from typing import Any, Callable, Optional, Type, Dict, List
29+
from typing import Any, Callable, Optional, Type, Dict, List, ContextManager
3030
from types import MemberDescriptorType, TracebackType
3131
from ._typing_compat import Literal
3232

@@ -54,9 +54,11 @@ class FuncProps:
5454
is_bound_method: bool
5555

5656

57-
class AttrCleaner:
57+
class AttrCleaner(ContextManager[None]):
5858
"""A context manager that tries to make an object not exhibit side-effects
59-
on attribute lookup."""
59+
on attribute lookup.
60+
61+
Unless explicitely required, prefer `getattr_safe`."""
6062

6163
def __init__(self, obj: Any) -> None:
6264
self._obj = obj
@@ -351,7 +353,7 @@ def get_encoding_file(fname: str) -> str:
351353

352354

353355
def getattr_safe(obj: Any, name: str) -> Any:
354-
"""side effect free getattr (calls getattr_static)."""
356+
"""Side effect free getattr (calls getattr_static)."""
355357
result = inspect.getattr_static(obj, name)
356358
# Slots are a MemberDescriptorType
357359
if isinstance(result, MemberDescriptorType):

0 commit comments

Comments
 (0)