1

I have a simple directory structure like so:

lib/
   dir1/
       __init__.py
       dir2/
           __init__.py
           file1.py
           file2.py
main.py

file1.py imports file2.py

main.py does from dir1.dir2.file1 import *. However, when I run main.py I get the following error:

No module named 'file2'

When I run file from dir2 it's fine. How does the python3 import system work?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
lee
  • 740
  • 2
  • 11
  • 24
  • 1
    it's well documentated here https://docs.python.org/3/reference/import.html – Lara Maia May 18 '18 at 18:17
  • 3
    Python 3 imports are *absolute* unless you use explicit relative imports. Use `from . import file2` or use `import dir1.dir2.file2` – Martijn Pieters May 18 '18 at 18:19
  • 4
    @LaraMaia: that document is way to in-depth and technical to give to someone just new to Python relative and absolute imports. – Martijn Pieters May 18 '18 at 18:19
  • Should `main.py` be indented one more level? – Mad Physicist May 18 '18 at 18:23
  • Can you post the entire error message? Its likely that `__init__.py` or `file1.py` is importing file2 and that's where the error is. It should be in the message. – tdelaney May 18 '18 at 18:23
  • 1
    @tdelaney: From the post: *`file1.py` imports `file2.py`* – Martijn Pieters May 18 '18 at 18:24
  • @MartijnPieters - quite right. If OP were to post the traceback we would see the import statement and could offer suggestions. Consider also that `__init__.py` could be importing the file so fixing file1 may not be sufficient. – tdelaney May 18 '18 at 18:26
  • @Martijn Pieters Ok, it's explained in-depth, but in a very simple way. I do not think this is way to technical. Sometimes it seems that people are lazy to read or afraid of the documentation. I do not feel good about this – Lara Maia May 18 '18 at 18:32
  • @LaraMaia As someone who has several years of experience in Python, I don't see an answer to the OPs question on the doc page. [PEP 328 (which is linked in the dupe target)](https://www.python.org/dev/peps/pep-0328/#guido-s-decision) is much clearer. – TemporalWolf May 18 '18 at 18:39
  • @Martijn Pieters the op question was "How does the python3 import system work?" and not "how do I solve this problem". You need to read better. – Lara Maia May 18 '18 at 18:48

0 Answers0