changeset 50784:65c1938fb9ff legacy-trunk

#1162154: inspect.getmembers() now skips attributes that raise AttributeError, e.g. a __slots__ attribute which has not been set.
author Amaury Forgeot d'Arc <amauryfa@gmail.com>
date Tue, 13 Jan 2009 23:39:22 +0000
parents a858b61db324
children bcf6663c5c04
files Lib/inspect.py Lib/test/test_inspect.py Misc/NEWS
diffstat 3 files changed, 19 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/Lib/inspect.py	Tue Jan 13 23:19:08 2009 +0000
+++ b/Lib/inspect.py	Tue Jan 13 23:39:22 2009 +0000
@@ -253,7 +253,10 @@
     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()
--- a/Lib/test/test_inspect.py	Tue Jan 13 23:19:08 2009 +0000
+++ b/Lib/test/test_inspect.py	Tue Jan 13 23:39:22 2009 +0000
@@ -91,6 +91,17 @@
         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)
--- a/Misc/NEWS	Tue Jan 13 23:19:08 2009 +0000
+++ b/Misc/NEWS	Tue Jan 13 23:39:22 2009 +0000
@@ -137,7 +137,10 @@
 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.