Why python can't import a path by using a relative path like "../hi.py"

I think “…hi” is hard for human to understand.

When I use package structure, even if two files are in the same level of a folder, they still can’t import each other.

❯ poetry run app
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/opt/homebrew/Cellar/python@3.10/3.10.10/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/Users/yingshaoxo/CS/it_has_alternatives/backend_service/backend_service/main.py", line 5, in <module>
    import backend_service.generated_yrpc.it_has_alternatives_rpc as it_has_alternatives_rpc
  File "/Users/yingshaoxo/CS/it_has_alternatives/backend_service/backend_service/generated_yrpc/it_has_alternatives_rpc.py", line 1, in <module>
    from it_has_alternatives_objects import *
ModuleNotFoundError: No module named 'it_has_alternatives_objects'

It may not look ideal to you (you could also consider absolute imports, or not so many layers of nesting), but implict relative imports (what you’re suggesting) are harder for humans to understand than explicit or absolute imports, which is why they were deliberately removed in Python 3. Without that, it is impossible for a human not already very familiar with the code base to determine whether a given import is absolute or relative just looking at the source file; they have to know or carefully examine the context. Furthermore confusion results if you have a package/module in the current directory that happens to have the same name as another (perhaps a transient dependency) that you or a user happens to have installed.

Fore more reasons, see, e.g. this SE question.

1 Like

Python does support realtive imports, but only inside pacakges (i.e. there’s an init.py in the dir).

Have you tried:

from .a_module import some_name ?

See: Python for the Lab | Complete Guide to Imports in Python: Absolute, Relative, and More

(just one google hit …)

NB, I assumed the user was referring to explicit relative imports when they lead with

I.e. an explicit relative import of a module named hi.py (as in the title) a couple levels up (as suggested by their screenshot), and were thus already aware of them, but objected to the syntax as being too “hard for [a] human to understand” vs. implicit relative imports. However, I may have been mistaken.