pythoninspect

Python - How get all attributes of a functions/class with inspect


I have two files : my_file.py and test.py.

my_file.py :

def heelo_friends():
    random_var = 56

class Attack:
    ss = 741
    def the_function():
        pass

test.py :

import my_file as mf
import inspect 
import sys 
    
    def get_classes(self) -> list:
        classes = []
        for x in dir(mf):
            obj = getattr(mf,x)
            if inspect.isclass(obj):
                classes.append(x)
                
        return f"All classes : {classes}"
        # All classes : ['Attack']

This file get all Classes from my_file.py. Now I want get all attributes from this classes (vars/methods etc ...)

How can I do that with inspect module ?


Solution

  • Here is a solution using inspect.getmembers:

    # my_file.py
    def heelo_friends():
        random_var = 56
    
    class Attack:
        ss = 741
        def the_function():
            pass
    
    
    # test.py
    import my_file as mf
    import inspect 
    import sys 
    
    def get_classes(self) -> list:
        classes = []
        for x in dir(mf):
            obj = getattr(mf,x)
            if inspect.isclass(obj):
                classes.append(x)
    
        return f"All classes : {classes}"
    
    attack = mf.Attack()
    attributes = inspect.getmembers(attack, lambda x:not(inspect.isroutine(x)))
    print("Attributes:", attributes)
    

    Output:

    Attributes: [('__class__', <class 'my_file.Attack'>), ('__delattr__', <method-wrapper '__delattr__' of Attack object at 0x102bd8fd0>), ('__dict__', {}), ('__doc__', None), ('__eq__', <method-wrapper '__eq__' of Attack object at 0x102bd8fd0>), ('__ge__', <method-wrapper '__ge__' of Attack object at 0x102bd8fd0>), ('__getattribute__', <method-wrapper '__getattribute__' of Attack object at 0x102bd8fd0>), ('__gt__', <method-wrapper '__gt__' of Attack object at 0x102bd8fd0>), ('__hash__', <method-wrapper '__hash__' of Attack object at 0x102bd8fd0>), ('__init__', <method-wrapper '__init__' of Attack object at 0x102bd8fd0>), ('__le__', <method-wrapper '__le__' of Attack object at 0x102bd8fd0>), ('__lt__', <method-wrapper '__lt__' of Attack object at 0x102bd8fd0>), ('__module__', 'my_file'), ('__ne__', <method-wrapper '__ne__' of Attack object at 0x102bd8fd0>), ('__repr__', <method-wrapper '__repr__' of Attack object at 0x102bd8fd0>), ('__setattr__', <method-wrapper '__setattr__' of Attack object at 0x102bd8fd0>), ('__str__', <method-wrapper '__str__' of Attack object at 0x102bd8fd0>), ('__weakref__', None), ('ss', 741)]