Import parent directory package without sys.path.append

Question:

I have a project structured as this:

parent/
   sub1/
      __init__.py
      directoryManager.py
   sub2
      tst.py

in tst.py, I am trying to import directoryManager as ld from sub1,
is there anyway to import it without using sys.path.append ?

Thanks very much

Asked By: Jialiang Zhou

||

Answers:

You could use:

from .. import directoryManager

The extra . goes one dictionary up

If this is going to be a package installed to path from parent parent.sub1 import directoryManager

Answered By: Xantium
import os
import sys

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sub1 import directoryManager

This should work.

Answered By: chemical

Recipe 1

import importlib.machinery
import importlib.util
import sys
from pathlib import Path

finder = importlib.machinery.PathFinder()
spec = finder.find_spec(
    'directoryManager',
    [str(Path(__file__).resolve().parent.parent / 'sub1')]
)
# or finder.find_spec('directoryManager', ['../sub1']) if cwd is sub2
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)

This recipe doesn’t need the full path of the file. Thus it is useful for importing extensions (they have suffixes like .cpython-38-aarch64-linux-gnu.so).

Recipe 2

import importlib.util
import sys
from pathlib import Path

spec = finder.spec_from_file_location(
    'directoryManager',
    str(Path(__file__).resolve().parent.parent / 'sub1' / 'directoryManager.py')
)
# or finder.spec_from_file_location('directoryManager, '../sub1/directoryManager.py') if cwd is sub2
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)

This recipe is more straightforward and simple.
Adapted from https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly

Reference

https://docs.python.org/3/library/importlib.html#checking-if-a-module-can-be-imported
(importlib.util.find_spec internally use PathFinder.find_spec)

Answered By: YouJiacheng
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.