Home > Enterprise >  python - import only when required?
python - import only when required?

Time:03-01

In my case the Python program has some kind of mods and some mods require special imports. If a mode is not activated at startup, these mode-specific imports should not be checked.

The goal is to start the Python program without the imports, when these are not required for the mode.

Even if I move the import to a separate (mode specific) class, which is not called, an import error message comes up.

Can this be implemented at all?

update:

This seems to work, thanks! @ amir zareian

    if __name__ == '__main__':        
        if mode:
          import testimport

The other option looks a bit more elegant to me, but the import is not recognized, I tried:

class ImportRequired:

    def __init__(self):
        import testimport

    def function(self):
        testimport.testcall()

CodePudding user response:

did you try to put that input in if condition ? or in switch case ? for example :

if (mode1):
    import first

and go on

  • Related