Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 86a8a9a

Browse files
committed
Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Also fixes issue #13581: `help(type)` wouldn't display anything.
1 parent 53aa1d7 commit 86a8a9a

4 files changed

Lines changed: 151 additions & 38 deletions

File tree

Lib/inspect.py

Lines changed: 46 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -100,11 +100,11 @@ def ismethoddescriptor(object):
100100
tests return false from the ismethoddescriptor() test, simply because
101101
the other tests promise more -- you can, e.g., count on having the
102102
__func__ attribute (etc) when an object passes ismethod()."""
103-
return (hasattr(object, "__get__")
104-
and not hasattr(object, "__set__") # else it's a data descriptor
105-
and not ismethod(object) # mutual exclusion
106-
and not isfunction(object)
107-
and not isclass(object))
103+
if isclass(object) or ismethod(object) or isfunction(object):
104+
# mutual exclusion
105+
return False
106+
tp = type(object)
107+
return hasattr(tp, "__get__") and not hasattr(tp, "__set__")
108108

109109
def isdatadescriptor(object):
110110
"""Return true if the object is a data descriptor.
@@ -114,7 +114,11 @@ def isdatadescriptor(object):
114114
Typically, data descriptors will also have __name__ and __doc__ attributes
115115
(properties, getsets, and members have both of these attributes), but this
116116
is not guaranteed."""
117-
return (hasattr(object, "__set__") and hasattr(object, "__get__"))
117+
if isclass(object) or ismethod(object) or isfunction(object):
118+
# mutual exclusion
119+
return False
120+
tp = type(object)
121+
return hasattr(tp, "__set__") and hasattr(tp, "__get__")
118122

119123
if hasattr(types, 'MemberDescriptorType'):
120124
# CPython and equivalent
@@ -254,12 +258,23 @@ def isabstract(object):
254258
def getmembers(object, predicate=None):
255259
"""Return all members of an object as (name, value) pairs sorted by name.
256260
Optionally, only return members that satisfy a given predicate."""
261+
if isclass(object):
262+
mro = (object,) + getmro(object)
263+
else:
264+
mro = ()
257265
results = []
258266
for key in dir(object):
259-
try:
260-
value = getattr(object, key)
261-
except AttributeError:
262-
continue
267+
# First try to get the value via __dict__. Some descriptors don't
268+
# like calling their __get__ (see bug #1785).
269+
for base in mro:
270+
if key in base.__dict__:
271+
value = base.__dict__[key]
272+
break
273+
else:
274+
try:
275+
value = getattr(object, key)
276+
except AttributeError:
277+
continue
263278
if not predicate or predicate(value):
264279
results.append((key, value))
265280
results.sort()
@@ -295,30 +310,21 @@ def classify_class_attrs(cls):
295310
names = dir(cls)
296311
result = []
297312
for name in names:
298-
# Get the object associated with the name.
313+
# Get the object associated with the name, and where it was defined.
299314
# Getting an obj from the __dict__ sometimes reveals more than
300315
# using getattr. Static and class methods are dramatic examples.
301-
if name in cls.__dict__:
302-
obj = cls.__dict__[name]
316+
# Furthermore, some objects may raise an Exception when fetched with
317+
# getattr(). This is the case with some descriptors (bug #1785).
318+
# Thus, we only use getattr() as a last resort.
319+
homecls = None
320+
for base in (cls,) + mro:
321+
if name in base.__dict__:
322+
obj = base.__dict__[name]
323+
homecls = base
324+
break
303325
else:
304326
obj = getattr(cls, name)
305-
306-
# Figure out where it was defined.
307-
homecls = getattr(obj, "__objclass__", None)
308-
if homecls is None:
309-
# search the dicts.
310-
for base in mro:
311-
if name in base.__dict__:
312-
homecls = base
313-
break
314-
315-
# Get the object again, in order to get it from the defining
316-
# __dict__ instead of via getattr (if possible).
317-
if homecls is not None and name in homecls.__dict__:
318-
obj = homecls.__dict__[name]
319-
320-
# Also get the object via getattr.
321-
obj_via_getattr = getattr(cls, name)
327+
homecls = getattr(obj, "__objclass__", homecls)
322328

323329
# Classify the object.
324330
if isinstance(obj, staticmethod):
@@ -327,11 +333,18 @@ def classify_class_attrs(cls):
327333
kind = "class method"
328334
elif isinstance(obj, property):
329335
kind = "property"
330-
elif (isfunction(obj_via_getattr) or
331-
ismethoddescriptor(obj_via_getattr)):
336+
elif ismethoddescriptor(obj):
332337
kind = "method"
333-
else:
338+
elif isdatadescriptor(obj):
334339
kind = "data"
340+
else:
341+
obj_via_getattr = getattr(cls, name)
342+
if (isfunction(obj_via_getattr) or
343+
ismethoddescriptor(obj_via_getattr)):
344+
kind = "method"
345+
else:
346+
kind = "data"
347+
obj = obj_via_getattr
335348

336349
result.append(Attribute(name, kind, homecls, obj))
337350

Lib/pydoc.py

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -754,8 +754,15 @@ def spill(msg, attrs, predicate):
754754
hr.maybe()
755755
push(msg)
756756
for name, kind, homecls, value in ok:
757-
push(self.document(getattr(object, name), name, mod,
758-
funcs, classes, mdict, object))
757+
try:
758+
value = getattr(object, name)
759+
except Exception:
760+
# Some descriptors may meet a failure in their __get__.
761+
# (bug #1785)
762+
push(self._docdescriptor(name, value, mod))
763+
else:
764+
push(self.document(value, name, mod,
765+
funcs, classes, mdict, object))
759766
push('\n')
760767
return attrs
761768

@@ -796,7 +803,12 @@ def spilldata(msg, attrs, predicate):
796803
mdict = {}
797804
for key, kind, homecls, value in attrs:
798805
mdict[key] = anchor = '#' + name + '-' + key
799-
value = getattr(object, key)
806+
try:
807+
value = getattr(object, name)
808+
except Exception:
809+
# Some descriptors may meet a failure in their __get__.
810+
# (bug #1785)
811+
pass
800812
try:
801813
# The value may not be hashable (e.g., a data attr with
802814
# a dict or list value).
@@ -1180,8 +1192,15 @@ def spill(msg, attrs, predicate):
11801192
hr.maybe()
11811193
push(msg)
11821194
for name, kind, homecls, value in ok:
1183-
push(self.document(getattr(object, name),
1184-
name, mod, object))
1195+
try:
1196+
value = getattr(object, name)
1197+
except Exception:
1198+
# Some descriptors may meet a failure in their __get__.
1199+
# (bug #1785)
1200+
push(self._docdescriptor(name, value, mod))
1201+
else:
1202+
push(self.document(value,
1203+
name, mod, object))
11851204
return attrs
11861205

11871206
def spilldescriptors(msg, attrs, predicate):

Lib/test/test_inspect.py

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -425,10 +425,37 @@ def tearDown(self):
425425
def test_class(self):
426426
self.assertSourceEqual(self.fodderModule.X, 1, 2)
427427

428+
429+
class _BrokenDataDescriptor(object):
430+
"""
431+
A broken data descriptor. See bug #1785.
432+
"""
433+
def __get__(*args):
434+
raise AssertionError("should not __get__ data descriptors")
435+
436+
def __set__(*args):
437+
raise RuntimeError
438+
439+
def __getattr__(*args):
440+
raise AssertionError("should not __getattr__ data descriptors")
441+
442+
443+
class _BrokenMethodDescriptor(object):
444+
"""
445+
A broken method descriptor. See bug #1785.
446+
"""
447+
def __get__(*args):
448+
raise AssertionError("should not __get__ method descriptors")
449+
450+
def __getattr__(*args):
451+
raise AssertionError("should not __getattr__ method descriptors")
452+
453+
428454
# Helper for testing classify_class_attrs.
429455
def attrs_wo_objs(cls):
430456
return [t[:3] for t in inspect.classify_class_attrs(cls)]
431457

458+
432459
class TestClassesAndFunctions(unittest.TestCase):
433460
def test_newstyle_mro(self):
434461
# The same w/ new-class MRO.
@@ -525,6 +552,9 @@ def m1(self): pass
525552

526553
datablob = '1'
527554

555+
dd = _BrokenDataDescriptor()
556+
md = _BrokenMethodDescriptor()
557+
528558
attrs = attrs_wo_objs(A)
529559
self.assertIn(('s', 'static method', A), attrs, 'missing static method')
530560
self.assertIn(('c', 'class method', A), attrs, 'missing class method')
@@ -533,6 +563,8 @@ def m1(self): pass
533563
'missing plain method: %r' % attrs)
534564
self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
535565
self.assertIn(('datablob', 'data', A), attrs, 'missing data')
566+
self.assertIn(('md', 'method', A), attrs, 'missing method descriptor')
567+
self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor')
536568

537569
class B(A):
538570

@@ -545,6 +577,8 @@ def m(self): pass
545577
self.assertIn(('m', 'method', B), attrs, 'missing plain method')
546578
self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
547579
self.assertIn(('datablob', 'data', A), attrs, 'missing data')
580+
self.assertIn(('md', 'method', A), attrs, 'missing method descriptor')
581+
self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor')
548582

549583

550584
class C(A):
@@ -559,6 +593,8 @@ def c(self): pass
559593
self.assertIn(('m', 'method', C), attrs, 'missing plain method')
560594
self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
561595
self.assertIn(('datablob', 'data', A), attrs, 'missing data')
596+
self.assertIn(('md', 'method', A), attrs, 'missing method descriptor')
597+
self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor')
562598

563599
class D(B, C):
564600

@@ -571,6 +607,49 @@ def m1(self): pass
571607
self.assertIn(('m', 'method', B), attrs, 'missing plain method')
572608
self.assertIn(('m1', 'method', D), attrs, 'missing plain method')
573609
self.assertIn(('datablob', 'data', A), attrs, 'missing data')
610+
self.assertIn(('md', 'method', A), attrs, 'missing method descriptor')
611+
self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor')
612+
613+
def test_classify_builtin_types(self):
614+
# Simple sanity check that all built-in types can have their
615+
# attributes classified.
616+
for name in dir(__builtins__):
617+
builtin = getattr(__builtins__, name)
618+
if isinstance(builtin, type):
619+
inspect.classify_class_attrs(builtin)
620+
621+
def test_getmembers_descriptors(self):
622+
class A(object):
623+
dd = _BrokenDataDescriptor()
624+
md = _BrokenMethodDescriptor()
625+
626+
def pred_wrapper(pred):
627+
# A quick'n'dirty way to discard standard attributes of new-style
628+
# classes.
629+
class Empty(object):
630+
pass
631+
def wrapped(x):
632+
if '__name__' in dir(x) and hasattr(Empty, x.__name__):
633+
return False
634+
return pred(x)
635+
return wrapped
636+
637+
ismethoddescriptor = pred_wrapper(inspect.ismethoddescriptor)
638+
isdatadescriptor = pred_wrapper(inspect.isdatadescriptor)
639+
640+
self.assertEqual(inspect.getmembers(A, ismethoddescriptor),
641+
[('md', A.__dict__['md'])])
642+
self.assertEqual(inspect.getmembers(A, isdatadescriptor),
643+
[('dd', A.__dict__['dd'])])
644+
645+
class B(A):
646+
pass
647+
648+
self.assertEqual(inspect.getmembers(B, ismethoddescriptor),
649+
[('md', A.__dict__['md'])])
650+
self.assertEqual(inspect.getmembers(B, isdatadescriptor),
651+
[('dd', A.__dict__['dd'])])
652+
574653

575654
class TestGetcallargsFunctions(unittest.TestCase):
576655

Misc/NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,8 @@ Core and Builtins
9797
Library
9898
-------
9999

100+
- Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
101+
100102
- Issue #11813: Fix inspect.getattr_static for modules. Patch by Andreas
101103
Stührk.
102104

0 commit comments

Comments
 (0)