This is a question I have seen asked in many places, but not answered fully. I am using Python 3.7+. I want to understand how to import a class into another file which is in any subdirectory. For example, if I have the following:
App
|
Trending
|
__init__.py
Trending.py (holds Trending class, and get_trending function)
TrendingUtils
|
__init__.py
TrendingUtils.py (holds TrendingUtils class and get_trend_utils function)
Utils
|
__init__.py
Utils.py (holds Utils class, get_utils function)
Top
|
__init__.py
Top.py (holds Top class and get_top function)
TopUtils
|
__init__.py
TopUtils.py (holds TopUtils class and get_top_utils function)
__init__.py
- How can I import the get_trending_utils function in the Trending.py file?
- How can I import the get_trending_utils function in the Utils.py file?
- How can I import the get_trending_utils function in the TopUtils.py file?
- How can I use Utils.py (and its functions) in both Trending.py and Top.py?
- How can I use get_top_utils in Trending.py?
The same questions go the deeper in subdirectories we go. I have read in different places that using the sys module can achieve this, but it seems clunky and not like best practice. I would like to do something like this, if possible:
In Trending.py:
import TrendingUtils
import Utils
var = TrendingUtils.get_trend_utils()
utils = Utils.get_utils()
also:
In Top.py
import Utils
import TrendingUtils
Import TopUtils
var1 = TrendingUtils.get_trend_utils()
var2 = Utils.get_utils()
var3 = TopUtils.get_top_utils.py
in TopUtils.py
from .. import TrendingUtils
from . import Top
var1 = TrendingUtils.get_trending_utils()
var2 = Top.get_top()
The init.py files are all emppty files. I have also seen that adding '.' will move up one directory, but trying something like
in Top.py
from . import Utils
from Trending import TrendingUtils
Also gives me errors. I have tried all possible combinations of the above as I can think of. I have also tried adding imports to the init.py files, but I keep getting the import errors. The only solution that seems to work is doing something like:
In Trending.py
PROJECT_ROOT = os.path.abspath(os.path.join(
os.path.dirname(__file__),
os.pardir)
)
sys.path.append(PROJECT_ROOT)
from Utils import get_utils
Again, this seems very clunky and dirty, and more importantly, not scalable to other OSs and other systems/computers. There must be a better way and I am just missing it. Thank you so much for the help.