0

I have four projects. Three of them (A, B, C) have custom Python module (which has same name but there are differences in functionality) that fourth project (D) is using.

In project D I need to import that module, but which (from project A, B or C) will be imported depends on provided path. How can I achieve this? I have this (pseudo)code:

import mymodule

# code

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(--path)

    path = args[0].path
    # now I need to use this variable 'path' to insert it to sys.path so that `import mymodule` will work
    sys.path.insert(0, path)

This, of course, won't work because Python interprets code line by line from the beginning of file. So it will throw exception ModuleNotFoundError.

Is there some way to achieve this except adding this part of code with argparser at the top of file before line `import mymodule'?

dosvarog
  • 694
  • 1
  • 6
  • 20
  • 2
    You can put `import mymodule` _after_ setting the `sys.path`. – Green Cloak Guy Aug 20 '21 at 15:19
  • 1
    Just move the import line down – user2390182 Aug 20 '21 at 15:19
  • 1
    You could use `importlib` - see [How to import a module given the full path?](https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path) - but it's not really any better than just moving the import statement below the argparse logic (you may as well remove the `if __name__ == '__main__':` guard too, it's not helping anything here) – wim Aug 20 '21 at 15:20
  • You all are very correct, I don't know why didn't I think of just moving `import mymodule` after setting `sys.path` in `if __name__ == '__main__'`. Now I am a bit embarrassed. I guess this is sign to go home, it is Friday and end of workday here, after all. Thank you all once more. – dosvarog Aug 20 '21 at 15:40

0 Answers0