how to discover a class's instance level fields given a class name

64 Views Asked by At

Given the following class Mock, I want to write a function get_members that returns a and b when the input is the class Mock. This task is easy if you are allowed to use an object of Mock as the input of this function to be written ( you can use "_ dict_" or vars or inspect etc), but looks impossible if Mock (the class Mock itself rather than an object of Mock) is used as the input as neither vars, dir or inspect has knowledge on the existence of field a.

class Mock:
    def __init__(self, a):
        self.a=a

    def b():
        pass

def get_members(clz):
    """return all the members of clz and its instance, including static methods, 
       class methods, instance level methods and fields
       e.g., given Mock, return a and b
    """
1

There are 1 best solutions below

1
AudioBubble On

I don;t know if I understood what you want

But you can have a method in your class Mock with a special unusual name (eg: someRandomMethodName122345)

When you get a param, try to call this method from the param, if the call returns True it means that the parameter has a method called someRandomMethodName122345, so it's probably a Mock (more probable if you call the method a random name unlikely to be present in any other class.

If you get an exception, the parameter is not a Mock instance

class Mock:
    def __init__(self, a):
        self.a = a

    @staticmethod
    def someRandomMethodName122345():
        return True

    def checkMockInstance(self, param):
        # checks if param is a Mock instance
        try:
            if param.someRandomMethodName122345():
                # param most likely is a mock instance, return self.a
                return self.a
        except AttributeError:
            # param is surely not a Mock instance, return false?
            return False

You haven;t defined what needs to be done if param is not a mock instance, in this example I return False, but this makes the return type inconsistent: sometimes False is returned, sometimes a is returned (whatever a is)