__getattr__特殊方法在Python 3.x中破坏inspect.getmembers()的变通办法

时间:2019-02-01 11:34:28

标签: python python-3.x inspect

与定义inspect.getmembers方法的类一起使用时,__getattr__函数会中断(在Python 3.x中):

import inspect

class C:
    def __getattr__(self, name):
        def wrapper():
            print("For MCVE purposes, this does nothing useful.")
        return wrapper

print(inspect.getmembers(C()))

产生的错误如下:

Traceback (most recent call last):
  File "tmp.py", line 9, in <module>
    print(inspect.getmembers(C()))
  File "/usr/lib/python3.7/inspect.py", line 330, in getmembers
    for base in object.__bases__:
TypeError: 'function' object is not iterable

问题似乎在于,inspect.getmodule依赖更轻松地请求宽恕方法,并假设__bases__属性要么不存在(抛出AttributeError异常)或包含基类。

我可以通过将AttributeError显式地扔到C.__getattr__中来解决此问题;但是,我想对无法控制的类的对象使用inspect.getmembers。我的问题是:没有解决方案,可以在不对类C或其实例进行任何修改的情况下解决该问题吗?

2 个答案:

答案 0 :(得分:1)

您要求一种解决方法,该解决方法无需修改C类或其实例即可。尽管这涉及重写长的getmembers()函数,但这还是很不方便的,尽管这是一个可行的解决方案。也许这更适合于库中的“拉取请求”。

(来自https://github.com/python/cpython/blob/3.7/Lib/inspect.py的源代码)

import inspect

def getmembers(object, predicate=None):
    """Return all members of an object as (name, value) pairs sorted by name.
    Optionally, only return members that satisfy a given predicate."""
    # Line below adds inspect. reference to isclass()
    if inspect.isclass(object):
        # Line below adds inspect. reference to getmro()
        mro = (object,) + inspect.getmro(object)
    else:
        mro = ()
    results = []
    processed = set()
    names = dir(object)
    # :dd any DynamicClassAttributes to the list of names if object is a class;
    # this may result in duplicate entries if, for example, a virtual
    # attribute with the same name as a DynamicClassAttribute exists
    try:
        for base in object.__bases__:
            for k, v in base.__dict__.items():
                if isinstance(v, types.DynamicClassAttribute):
                    names.append(k)
    # Line below edited to catch TypeError
    except (AttributeError, TypeError):
        pass
    for key in names:
        # First try to get the value via getattr.  Some descriptors don't
        # like calling their __get__ (see bug #1785), so fall back to
        # looking in the __dict__.
        try:
            value = getattr(object, key)
            # handle the duplicate key
            if key in processed:
                raise AttributeError
        except AttributeError:
            for base in mro:
                if key in base.__dict__:
                    value = base.__dict__[key]
                    break
            else:
                # could be a (currently) missing slot member, or a buggy
                # __dir__; discard and move on
                continue
        if not predicate or predicate(value):
            results.append((key, value))
        processed.add(key)
    results.sort(key=lambda pair: pair[0])
    return results

现在,如果您运行新的getmembers()

class C:
    def __getattr__(self, name):
        def wrapper():
            print("For MCVE purposes, this does nothing useful.")
        return wrapper

print(getmembers(C()))

您应该得到想要的结果:

[('__class__', <class '__main__.C'>), ('__delattr__', <method-wrapper '__delattr__' of C object at 0x1155fa7b8>), ('__dict__', {}), ('__dir__', <built-in method __dir__ of C object at 0x1155fa7b8>), ('__doc__', None), ('__eq__', <method-wrapper '__eq__' of C object at 0x1155fa7b8>), ('__format__', <built-in method __format__ of C object at 0x1155fa7b8>), ('__ge__', <method-wrapper '__ge__' of C object at 0x1155fa7b8>), ('__getattr__', <bound method C.__getattr__ of <__main__.C object at 0x1155fa7b8>>), ('__getattribute__', <method-wrapper '__getattribute__' of C object at 0x1155fa7b8>), ('__gt__', <method-wrapper '__gt__' of C object at 0x1155fa7b8>), ('__hash__', <method-wrapper '__hash__' of C object at 0x1155fa7b8>), ('__init__', <method-wrapper '__init__' of C object at 0x1155fa7b8>), ('__init_subclass__', <built-in method __init_subclass__ of type object at 0x7fd01899e4c8>), ('__le__', <method-wrapper '__le__' of C object at 0x1155fa7b8>), ('__lt__', <method-wrapper '__lt__' of C object at 0x1155fa7b8>), ('__module__', '__main__'), ('__ne__', <method-wrapper '__ne__' of C object at 0x1155fa7b8>), ('__new__', <built-in method __new__ of type object at 0x1008b0c48>), ('__reduce__', <built-in method __reduce__ of C object at 0x1155fa7b8>), ('__reduce_ex__', <built-in method __reduce_ex__ of C object at 0x1155fa7b8>), ('__repr__', <method-wrapper '__repr__' of C object at 0x1155fa7b8>), ('__setattr__', <method-wrapper '__setattr__' of C object at 0x1155fa7b8>), ('__sizeof__', <built-in method __sizeof__ of C object at 0x1155fa7b8>), ('__str__', <method-wrapper '__str__' of C object at 0x1155fa7b8>), ('__subclasshook__', <built-in method __subclasshook__ of type object at 0x7fd01899e4c8>), ('__weakref__', None)]

答案 1 :(得分:-1)

在致电c.__bases__ = ()之前尝试设置inspect.getmembers(c)

编辑:更安全,更详尽的版本以回应评论:

object.__setattr__(c, '__bases__', ())
try:
    members = inspect.getmembers(c)
finally:
    object.__delattr__(c, '__bases__')

在以下情况下,此操作将失败:

  1. C定义了__slots__或由于其他原因不允许设置__bases__,这会引发异常。
  2. c已经有一个实际的__bases__属性,不应覆盖。可以使用一些额外的代码来检查。