1

I have seen these sites:

python relative import example code does not work

Relative imports for the billionth time

https://peps.python.org/pep-0328/

Python packages: relative imports

Relative imports in Python

and loads more that I did not show, but they (The answers/The code) just don't work for some reason to relatively import other Python 'modules'. And for always, I have this forever-recurring error: ImportError: attempted relative import with no known parent package.

My directory structure looks like this:

program/
|_ main.py
|_ lib/
    |_ __init__.py
    |_ module1.py
    |_ module2.py
    |_ module3.py

In main.py:

from .lib.module1 import do_this
print('Imported')

In module1.py:

def do_this():
    print('I did it')

I'm using Linux to do this, but it just doesn't work!!!

EDIT:

I don't want to have to do python3 -m <module> main.py And apparently it still does not work without the dot.

  • 1
    You've linked multiple answers explaining why what you're trying to do can't work, unless main.py is a module being imported as a module. Those answers say you can't run "python main.py" and have a relative import in main.py. – Dan Getz Jun 08 '22 at 06:08
  • Either run it as a package / module, `python -m ` or just remove the leading dot and run it. If you run this as `python main.py` without the dot `from lib.module1 import do_this`, it will work. Otherwise the module is `__main__` and it can't resolve the relative package path. – theherk Jun 08 '22 at 06:15
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jun 08 '22 at 07:33
  • I'll try your comment's answers on a different Linux computer @theherk – linux-coding649 Jun 09 '22 at 04:08

0 Answers0