简体   繁体   English

Python inspect.getmembers不会返回所有成员吗?

[英]Python inspect.getmembers does not return all members?

Is this a bug in inspect.getmembers, or is this the expected behavior? 这是inspect.getmembers中的错误,还是预期的行为?

torch.bmm in inspect.getmembers(torch)
False

This isn't a bug; 这不是错误; this is inspect.getmembers doing exactly what it's documented to do: 这是inspect.getmembers完全按照记录做的事情:

Return all the members of an object in a list of (name, value) pairs sorted by name… 返回按名称对(名称,值)对的列表中的对象的所有成员…

So, ('bmm', torch.bmm) might be in such a list, but torch.bmm won't. 因此, ('bmm', torch.bmm)可能在这样的列表中,但是torch.bmm不会。


If you want to know if torch.bmm is a member of torch … well, you already know that it is, or torch.bmm would have raised an AttributeError . 如果您想知道torch.bmm是否是torch的成员……那么,您已经知道它是,否则torch.bmm会引发AttributeError But you can search the second (value) part of each pair: 但是您可以搜索每对的第二个(值)部分:

any(member == torch.bmm for name, member in inspect.getmembers(torch))

… or you can turn the list into a dict and search it: …或者您可以将列表变成字典并进行搜索:

torch.bmm in dict(inspect.getmembers(torch)).values()

But, again, the fact that torch.bmm didn't raise an exception is already enough to tell you that it exists. 但是,再次说明, torch.bmm没有引发异常的事实已经足以告诉您该异常存在。 If you want to handle the possibility that it doesn't, any checking you do after getting that exception is too late; 如果您想处理不这样做的可能性,那么在获得该异常之后进行的任何检查都为时已晚; you just want to handle the exception: 您只想处理异常:

try:
    torch.bmm
except AttributeError:
    # whatever you wanted to do if it doesn't exist
else:
    # whatever you wanted to do with torch.bmm 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM