Given a "path" and a "super_class", find all classes that are defined under the given "path" (recursively if directory)
that are subclass of given "super_class".
Follow following instructions while implementing above module.
Where possible breakdown the task into simpler subtask and implement them separately, eg. as functions.
Use descriptive names, short documentations along with the code to show whats going on.
Imports can be done in middle if required
The module should be self contained (Containing test cases, resources required for the test cases and the actual implementation)
If any resources are generated for test cases, cleanup when the testing ends.
Use following template for the implementation
name : <appropriate_file_name>.py
"""
Short summary of the module
"""
----- UNIT TESTS ----
...
IMPLEMENTATION
...
if name == 'main':
...
# unit tests invocation.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is the implementation of a Python module that fulfills the given requirements. The module is named subclass_finder.py. It contains functions to search for Python files, load classes from those files, and check if they are subclasses of the provided super_class. The module also includes unit tests to ensure the correctness of the implementation, and it cleans up any generated resources during the test cases.
python
# name: subclass_finder.py
"""
This module provides functionality to find all classes in a given path that are subclasses of a specified superclass.
It scans Python files recursively starting from the provided path and checks for subclass relationships.
"""
import os
import sys
import unittest
from importlib import import_module
from pathlib import Path
from shutil import rmtree
## ----- HELPER FUNCTIONS ----
def find_python_files(path):
"""Recursively find all Python files in the given path."""
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith('.py'):
yield os.path.join(root, file)
def import_class_from_file(file_path, class_name):
"""Import a class from a Python file given its file path and class name."""
module_name = os.path.splitext(os.path.basename(file_path))[0]
spec = import_module(module_name)
return getattr(spec, class_name, None)
def find_subclasses(path, super_class):
"""Find all classes in the given path that are subclasses of the provided super_class."""
subclasses = []
sys.path.insert(0, path) # Add to module search path
for py_file in find_python_files(path):
# Load module from the Python file
module_name = os.path.splitext(os.path.basename(py_file))[0]
module = import_module(module_name)
# Check each attribute of the module to find subclass of super_class
for attribute_name in dir(module):
attribute = getattr(module, attribute_name)
if isinstance(attribute, type) and issubclass(attribute, super_class) and attribute is not super_class:
subclasses.append(attribute)
sys.path.pop(0) # Remove path from module search path
return subclasses
## ----- UNIT TESTS ----
class TestSubclassFinder(unittest.TestCase):
test_dir = 'test_subclass_finder'
@classmethod
def setUpClass(cls):
# Create a directory for test modules
os.makedirs(cls.test_dir, exist_ok=True)
sys.path.insert(0, cls.test_dir)
# Create test modules
test_module_content = {
'module_a.py': 'class A: pass',
'module_b.py': 'from module_a import A\nclass B(A): pass',
'module_c.py': 'from module_a import A\nclass C: pass',
}
for file_name, content in test_module_content.items():
with open(os.path.join(cls.test_dir, file_name), 'w') as f:
f.write(content)
@classmethod
def tearDownClass(cls):
# Remove test directory and its contents
rmtree(cls.test_dir)
sys.path.remove(cls.test_dir)
def test_find_subclasses(self):
# Import the test super_class
A = import_class_from_file(os.path.join(self.test_dir, 'module_a.py'), 'A')
# Find subclasses of A
subclasses = find_subclasses(self.test_dir, A)
# Verify that B is a subclass of A, and C is not
self.assertTrue(any(cls.__name__ == 'B' for cls in subclasses))
self.assertFalse(any(cls.__name__ == 'C' for cls in subclasses))
## IMPLEMENTATION
# The implementation code has been provided in the helper functions and unit tests above.
if __name__ == '__main__':
unittest.main()
This module should be placed in a file named subclass_finder.py. When run, it will execute the unit tests to verify that it correctly finds subclasses of a given super_class within the specified path. The test cases create temporary Python files in a test directory, which is cleaned up after the tests are completed.