SoFunction
Updated on 2024-11-10

Python's implementation of automatic package importing

Problem description: During the code writing process, you need to introduce files, but the files introduced will become more and more as the project gets bigger, so you have written an automatic import method that will import the files according to the characteristics of their names.

def auto_import(packagePath: str, fileTag: str, interceptLength: int, level=1):
    """
    Auto-import function to import a file with a certain identifier
    :param packagePath: current package path
    :param level: package level
    :param fileTag: file name identification
    :param interceptLength: name of the intercepted import attribute
    :return.
    """
    # Define import attribute lists and packages
    att_list = []
    # Get the corresponding package hierarchy
    rank = level
    package = ''
    for i in range(level):
        # Get parent package name splice package name
        package += ('\\')[-rank] + '.'
        rank -= 1
    # Iterate over all files under the current package
    for fileName in (packagePath):
        # Filter out nameTag files for importing
        if fileTag in fileName:
            print(f'Import Package Name:{package}' + fileName[:-3])
            # Dynamically import the package and get the specific modules, properties within the package
            att_list.append(
                # Import an attribute from the package
                importlib.import_module(
                    # Splice module paths
                    f'{package}' + fileName[:-3]
                    # Get the corresponding attribute in the module
                ).__dict__[fileName[:-interceptLength]])
    # Returns a list of attributes
    return att_list

Suppose we create multiple TableModel files and need to verify that the corresponding files exist in the database, then we can use it like this:

import os
import auto_import


def auto_check_model():
    """
    Import all the files in the tableModel and verify that the table exists in the database.
    :return: Returns the validation results
    """
    # Get current folder path
    packagePath = ((__file__))
    # Get all mod files
    model_list = auto_import(packagePath=packagePath, fileTag='Model',  interceptLength=8, level=2)
    # Establishment of database connections
    connect = DatabaseOperation().connect()
    # Check if the model exists in the database, if it doesn't, create it.
    for i in range(len(model_list)):
        model_list[i].metadata.create_all(connect)
        print(f"####     {model_list[i].__name__}Calibration complete!    ####")

to this article on the realization of the python automatic import package is introduced to this article, more relevant python automatic import package content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!