0

I know there are many articles about this issue, but I still can not understand it clearly.

My file structure is like this:

── pkg
    ├── __init__.py
    ├── sub_pkg_A
    │       ├── __init__.py
    │       ├── module_in_A.py
    ├── sub_pkg_B
    │       ├── __init__.py
    │       ├── module_in_B.py

In module_in_B.py:

from ..sub_pkg_A import module_in_A
print('Successful!')

And execute:

$ cd pkg
$ python pkg/sub_pkg_B/module_in_B.py
Traceback (most recent call last):
  File "pkg/sub_pkg_B/module_in_B.py", line 1, in <module>
    from ..sub_pkg_A import module_in_A
ValueError: attempted relative import beyond top-level package
$ python -m pkg.sub_pkg_B.module_in_B
Successful!

Here is my question:

  1. Why python pkg/sub_pkg_B/module_in_B.py can not work? What is the top-level package in this situation and why?
  2. How can I fix this error when I run python pkg/sub_pkg_B/module_in_B.py? I know that sys.path.append('../') may be helpful but it doesn't work in my situation.
  3. Why python -m pkg.sub_pkg_B.module_in_B can work? I knew that -m flag is to "run library module as a script" but I'm not understand it clearly. And when should I use -m flag?

Sorry for lots questions. Any suggestions and answers are helpful. Thank you!

Chun-Ye Lu
  • 343
  • 1
  • 2
  • 10
  • in case of 1,2 questions you are running the script from the sub_pkg_b directory lvl, while in case 3 you are running it from pkg lvl, here, when you run script python is able to understand the sub directory in pkg while in case 1,2 it is unable to understand and throw the error – sahasrara62 Apr 06 '21 at 07:00
  • I think a similar solution has been given here https://stackoverflow.com/a/53918952/12529215 – Shorya Sharma Apr 06 '21 at 07:03

0 Answers0