gpt4 book ai didi

python - 解决 __getattr__ 特殊方法破坏 Python 3.x 中的 inspect.getmembers()

转载 作者:行者123 更新时间:2023-11-28 18:59:25 29 4
gpt4 key购买 nike

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 异常)或包含基类。

我可以通过在 C.__getattr__ 中显式抛出 AttributeError 来解决这个问题;但是,我想将 inspect.getmembers 与我无法控制的类的对象一起使用。我的问题是:是否有解决此问题的方法,无需对类 C 或其实例进行任何修改?

最佳答案

您要求提供一种无需修改类 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)]

关于python - 解决 __getattr__ 特殊方法破坏 Python 3.x 中的 inspect.getmembers(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54478679/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com