Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat] robust way of defining and importing the model class #158

Open
suzannejin opened this issue Jul 10, 2024 · 0 comments
Open

[feat] robust way of defining and importing the model class #158

suzannejin opened this issue Jul 10, 2024 · 0 comments
Labels
good to have Future features that are good to explore/have

Comments

@suzannejin
Copy link
Collaborator

Currently, the code will just read the model .py file, and check for the first class that starts with 'Model'.
However, this might lead to undesired behaviours (eg. the user may have defined many classes starting with Model, etc.).
Need a more robust way of doing it, or force a nomenclature.

def import_class_from_file(file_path: str) -> type:

    # Extract directory path and file name
    directory, file_name = os.path.split(file_path)
    module_name = os.path.splitext(file_name)[0]  # Remove extension to get module name
    
    # Create a module from the file path
    # In summary, these three lines of code are responsible for creating a module specification based on a file location, creating a module object from that specification, and then executing the module's code to populate the module object with the definitions from the Python file.
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    
    # Find the class dynamically
    for name in dir(module):
        model_class = getattr(module, name)
        if isinstance(model_class, type) and name.startswith('Model'):
            return model_class
    
    # Class not found
    raise ImportError("No class starting with 'Model' found in the file.")
@suzannejin suzannejin added this to the FUTURE milestone Jul 10, 2024
@suzannejin suzannejin added the good to have Future features that are good to explore/have label Jul 10, 2024
@mathysgrapotte mathysgrapotte removed this from the FUTURE milestone Sep 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good to have Future features that are good to explore/have
Projects
None yet
Development

No branches or pull requests

2 participants