Home > Back-end >  How to import all possible modules and pass ones that don't exist?
How to import all possible modules and pass ones that don't exist?

Time:06-02

Sorry if the title's confusing (feel free to edit if you think you can explain it better).

I want to import all modules (seperate python scripts) named A-H, but there is uncertainty about whether they will exist or not. I want to just ignore them if they don't exist and import them if they do.

I have worked out a way, but it's long and seems unnecessary, and I feel like there must be a better way to do it. Here's my code:

try:
    from scripts import A
except:
    pass
try:
    from scripts import B
except:
    pass
try:
    from scripts import C
except:
    pass
try:
    from scripts import D
except:
    pass
try:
    from scripts import E
except:
    pass
try:
    from scripts import F
except:
    pass
try:
    from scripts import G
except:
    pass
try:
    from scripts import H
except:
    pass

How can I tidy this up?

CodePudding user response:

Method 1:

Not the best practice, but you can try this:

from scripts import *

Note that this imports everything, and thus has a potential to substantially pollute your name space.

Method 2:

modules = 'A B C D E F G H'.split()
    for module in modules:
        try:
            globals()[module] = __import__(module)
        except:
            pass

CodePudding user response:

On my mind, your request itself is a little bit confusing without any context. In any case it seems that the follow up code will need a way to deal with the missing modules - I guess the have a purpose and are going to be used at some point.

To import "all" existing modules within scripts, just do:

from scripts import *

CodePudding user response:

import dynamically:

from importlib import import_module

libs = [chr(i) for i in range(ord("A"), ord("H")   1)]
loaded_modules = []
for lib in libs:
    try:
        loaded_modules.append(import_module(lib))
    except ModuleNotFoundError:
        pass

print(loaded_modules)

also you may want to save the module to a variable so you can do something with it

note that if you do this:

from scripts import *

you will need to define an __init__.py file which in itself will need to import all the modules which are present, as import * only imports the contents of python files, not the contents of directories, defeating the whole purpose of loading the modules dynamically.

  • Related