0

given the following file structure (example)

library_project\
 |- __init__.py
 |
 |--- utils_a\
 |     |- __init__.py
 |     |- util_functions_a.py
 |
 |--- utils_b\
 |     |- __init__.py
 |     |
 |     |--- utils_b_1\
 |     |     |- __init__.py
 |     |     |- util_function_b1.py
 |     |
 |     |--- utils_b_2\
 |     |     |- __init__.py
 |     |     |- util_function_b2.py

and a second project

other_project\
 |- __init__.py
 |- run.py

in run.py

from library_project.utils_b.util_function_b2 import do_something
do_something()

How can util_function_b2.py use functions from util_functions_a.py?

All examples for relative imports that I found assume that the imported package is a sibling package (e.g. https://docs.python.org/2/tutorial/modules.html#intra-package-references) and not 2 levels up

2 Answers2

1

The import statement allows you to use an arbitrary number of . dots to refer to packages further up the tree.

  • . refers to the same package; utils_b_2.
  • .. refers to the same shared parent package, utils_b
  • ... refers to library_project

From util_function_b2 you can refer to util_functions_a with 3 dots:

from ...utils_a.util_functions_a import somename
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
-1

Given the Directory structure, to import "util_function_b2.py"

from library_project.urils_b.utils_b_2.until_function_b2 import *

How can util_function_b2.py use functions from util_functions_a.py -

You can either add the project to python path.

sys.path.append('/path/to/library_project/')

then,

from  from library_project.utils_a imoprt *

or there is a way to do with relative addressing using "."

Bala
  • 381
  • 3
  • 16
  • Don't add the `library_project` folder to `sys.path`, you add the *parent* to `sys.path`. That's not the issue here however, the question is about how to use `..` relative module names in the `import` statement. – Martijn Pieters Jun 02 '14 at 12:28