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:
- 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 likeimport mod_1
.mod_1.py
in turn importsmod_2.py
asimport mod_2
. This is fine. - The files are also bundled up into a python package called
packagename
. In this context when I want to importmod_2.py
insidemod_1.py
I callimport 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