1

I want to look at a file and get the names of classes and check if the "Runconfig" name is inherited. So if a file has

class some_function(RunConfig):

I want to return true. My code looks like this right now:

for file in list_of_files:
   if file in ['some_file.py']:
       for name,obj in inspect.getmembers(file):
          if inspect.isclass(obj):
             print("NAME",name,"obj",obj)

This returns objects but I don't see anything that says 'RunConfig' on it. What am I missing here? Thank you so much in advance!

hope288
  • 725
  • 12
  • 23

1 Answers1

1

You can do something like:

import importlib
import inspect

def is_class_inherited_in_file(file_name, class_ref):
    module = importlib.import_module(file_name.split('.')[0])
    module_members = inspect.getmembers(module)
    for member in module_members:
        if type(member[1]) == type and issubclass(member[1], class_ref):
            return True
    return False

>>> is_class_inherited_in_file('some_file.py', RunConfig)
True

Assumption: The filename is in the working directory. If you would like to import from any directory, then do something like: How to import a module given the full path?

Amit Kumar
  • 830
  • 7
  • 17
  • thanks so much! I ended up using part of this. I used re.search to just look for the word config after grabbing the module and members `module = importlib.import_module(file.split('.')[0]) module_members = inspect.getmembers(module) for member in module_members: if re.search('runconfig', str(member[1]), re.IGNORECASE):` – hope288 Jun 23 '19 at 20:19
  • Do you by any chance know how I can grab a dictionary that is within the init of that file? I want to inspect the keys of the dictionary in the file that has that runconfig. Looking into inspect.getargvalues but not sure if this is the correct route and don't understand how to grab the frame. Thanks – hope288 Jun 23 '19 at 22:48
  • i'm not sure what I'm supposed to pass inside getargvalues since I don't want the current frame but the frame of the file of 'some_file' that passes the truth statement. – hope288 Jun 23 '19 at 23:09