Dynamic module import in Python



  • 3 Answer(s)

    With Python older than two.7/3.1, that is just about however you are doing it.

       For newer versions, see importlib.import_module for Python two and and Python three.

       You can use EXEC if you would like to in addition.
    Or victimization __import__ you’ll be able to import an inventory of modules by doing this:

    >>> moduleNames = ['sys', 'os', 're', 'unittest']
    >>> moduleNames
    ['sys', 'os', 're', 'unittest']
    >>> modules = map(__import__, moduleNames)
    
    Answered on October 20, 2018.
    Add Comment

             The counseled means for Python 2.7 and 3.1 and later is to use importlib module:

    importlib.import_module(name, package=None)
    

    Import a module.

            The name argument specifies what module to import in absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is laid out in relative terms, then the package argument should be set to the name of the package that is to act because the anchor for resolution the package name (e.g. import_module(‘..mod’, ‘pkg.subpkg’) can import pkg.mod).
    e.g.

    my_module = importlib.import_module('os.path')
    

     

    Answered on October 20, 2018.
    Add Comment

              As mentioned earlier the imp module provides you loading functions:

    imp.load_source(name, path)
    imp.load_compiled(name, path)
    

            I’ve used these before to perform one thing similar.
                   In my case I outlined a selected category with outlined strategies that were needed. Once I loaded the module i’d check if the            category was within the module, and so produce associate instance of that category, one thing like this:

    import imp
    import os
    def load_from_file(filepath):
        class_inst = None
        expected_class = 'MyClass'
        mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1])
        if file_ext.lower() == '.py':
            py_mod = imp.load_source(mod_name, filepath)
        elif file_ext.lower() == '.pyc':
            py_mod = imp.load_compiled(mod_name, filepath)
        if hasattr(py_mod, expected_class):
            class_inst = getattr(py_mod, expected_class)()
        return class_inst
    

    Answered on October 20, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.