0

I have a collection of .py files in the following file structure:

packagename\
    mod_1.py
    mod_2.py
    script_1.py
    etc.

These files do two things:

  1. They're bundled into an application (a JMP/JSL add-in, although not relevant here). In this application script_1.py is called, and it contains import statements like import mod_1. mod_1.py in turn imports mod_2.py as import mod_2. This is fine.
  2. The files are also bundled up into a python package called packagename. In this context when I want to import mod_2.py inside mod_1.py I call import packagename.mod_2. This is also fine.

I presently implement this in mod_1.py, very painfully, as:

if 'addin' in __file__:
    import mod_2
else:
    import packagename.mod_2

This works but I've got lots and lots of modules (more than just mod_1, mod_2). Is there a way to do something like this (pseudocode)?:

if 'addin' in __file__:
    import_prefix = ''
else:
    import_prefix = 'packagename.'

import import_prefix + mod_2

This answer seems to cover half of what I'm looking for, but not everything: Python: importing a sub‑package or sub‑module

Greg
  • 3,570
  • 5
  • 18
  • 31
  • Maybe you can use `importlib` to write a function that does this, so you just call the function instead of writing repeated `if` statements. – Barmar Jun 08 '23 at 17:04
  • `script_1.py` may be part of your *distribution* package, but it should not be part of the *import* package that contains `mod_1.py` and `mod_2.py`. The script should use `import packagename.mod_1`, with the script and package installed appropriately in each scenario. – chepner Jun 08 '23 at 17:18
  • Does this answer your question? [import module from string variable](https://stackoverflow.com/questions/8718885/import-module-from-string-variable) – mkrieger1 Jun 08 '23 at 17:18
  • Better duplicate: https://stackoverflow.com/questions/301134/how-can-i-import-a-module-dynamically-given-its-name-as-string – mkrieger1 Jun 08 '23 at 17:20

1 Answers1

1

You may just want to use importlib.import_module.

import importlib

def _import(module_name: str):
    if 'addin' in __file__:
        return importlib.import_module(module_name)
    return importlib.import_module(f'packagename.{module_name}')

mod_2 = _import(mod_2)
James
  • 32,991
  • 4
  • 47
  • 70