From b54447f31cf8f590ef526d2707f26041720f5784 Mon Sep 17 00:00:00 2001 From: Amaury Forgeot d'Arc Date: Tue, 13 Jan 2009 23:39:22 +0000 Subject: #1162154: inspect.getmembers() now skips attributes that raise AttributeError, e.g. a __slots__ attribute which has not been set. --- Lib/inspect.py | 5 ++++- Lib/test/test_inspect.py | 11 +++++++++++ Misc/NEWS | 5 ++++- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/Lib/inspect.py b/Lib/inspect.py index 1685bfc..8268be1 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -253,7 +253,10 @@ def getmembers(object, predicate=None): Optionally, only return members that satisfy a given predicate.""" results = [] for key in dir(object): - value = getattr(object, key) + try: + value = getattr(object, key) + except AttributeError: + continue if not predicate or predicate(value): results.append((key, value)) results.sort() diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py index 300d143..b653f40 100644 --- a/Lib/test/test_inspect.py +++ b/Lib/test/test_inspect.py @@ -91,6 +91,17 @@ class TestPredicates(IsTestBase): self.assert_(inspect.isroutine(mod.spam)) self.assert_(inspect.isroutine([].count)) + def test_get_slot_members(self): + class C(object): + __slots__ = ("a", "b") + + x = C() + x.a = 42 + members = dict(inspect.getmembers(x)) + self.assert_('a' in members) + self.assert_('b' not in members) + + class TestInterpreterStack(IsTestBase): def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) diff --git a/Misc/NEWS b/Misc/NEWS index 7939323..9ced73d 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -137,7 +137,10 @@ Core and Builtins Library ------- -- Issue #1696199: Add collections.Counter() for rapid and convenient +- Issue #1162154: inspect.getmembers() now skips attributes that raise + AttributeError, e.g. a __slots__ attribute which has not been set. + +- Issue #1696199: Add collections.Counter() for rapid and convenient counting. - Issue #3860: GzipFile and BZ2File now support the context manager protocol. -- cgit v0.12