0

I have this structure:

F
 f1
 __init__.py
 f.py
 g.py
 f2
 __init__.py
 h.py

f2.__init__.py:

from f1 import f, g

f2.h.py:

from f2 import f, g

f2.py is a __main__ file. When i run f2, I get the error

ModuleNotFoundError: No module named 'f2'

How can I fix that?

phrogg
9081 gold badge13 silver badges28 bronze badges
asked Aug 22, 2018 at 8:23
3
  • python version? Commented Aug 22, 2018 at 8:39
  • @MiloLu 3.7.0 is the version Commented Aug 22, 2018 at 8:43
  • Why import g from f2 when it don't contains g? Commented Aug 22, 2018 at 8:47

2 Answers 2

1

if you are running main in the f2.h.py directly the interpreter does not seem the parent path to F.

An option is to use relative imports which are different for Python 2/3. For example, add F.__init__.py file, then chnage F.f2.__init__.py to from ..f1 import f, g and finaly in F.f2.h.py import as from F.f2 import f, g.

Another option is adding the path to the parent destination:

import os, sys
sys.path += [os.path.abspath('..')]
from f2 import f, g
if __name__ == '__main__':
 print('hello')
answered Aug 22, 2018 at 8:49
Sign up to request clarification or add additional context in comments.

3 Comments

i used relative imports and this is what i always get an error. when i do from . import f, g, i get an ImportError which says cannot import f from __main__ and when i do from .. import f, g i get an ValueError which says attempted relative import beyond top-level package
please specify what Python you are using
I use python 3.7.0
0

I fix it. As Jirka B. said, the problem was i run the code directley from the interpreter. After doing what should be done, everything works as i like. Thx guys.

answered Aug 22, 2018 at 13:13

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.