Search code examples
pythontorch

Python inspect.getmembers does not return all members?


Is this a bug in inspect.getmembers, or is this the expected behavior?

torch.bmm in inspect.getmembers(torch)
False

Solution

  • This isn't a bug; this is inspect.getmembers doing exactly what it's documented to do:

    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.


    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. 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. 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