1

I am writing a sequence to sequence model and I have the following directory structure

MyProject/ models/ - __init__.py - Encoder.py train/ - __init__.py - Train.py 

While in Train.py, I cannot import the classes BiDirectionalEncoder from Encoder.py despite trying to use the following syntax

from models.Encoder import BiDirectionalEncoder 

For the line above I get the error " ModuleNotFoundError: No module named 'models'"

from ..models.Encoder import BiDirectionalEncoder 

For the last line I get the error "ImportError: attempted relative import with no known parent package"

Is there are neat way to fix this? I dont want to use any sys.path.append() to force paths to be added I am using Python 3.7.6 in Spyder 4.0.1 Thanks!

9
  • 1
    from models.Encoder import BiDirectionalEncoder is it not working? Commented Feb 12, 2020 at 10:09
  • No its not. And that is a bit frustrating and surprising too, I cant figure out what is wrong. Commented Feb 12, 2020 at 10:10
  • what is your current directory file when you run the program? if you are trying to run from Train.py then the system can't find the main My project path. Commented Feb 12, 2020 at 10:32
  • @Wajih were you able to fix this issue? Commented Feb 13, 2020 at 11:01
  • 1
    I tried. Seems that this a problem with Spyder. Thanks for the solution thought. Commented Feb 14, 2020 at 7:14

2 Answers 2

1

Within the same package you can do relative import but since you are going out of your current package, you need to do absolute imports.

from MyProject.models.Encoder import BiDirectionalEncoder 
Sign up to request clarification or add additional context in comments.

4 Comments

You mean I add the project path name to the imports? That is going to be clunky. I am not sure. Let me try this.
Yes, as the error message suggest.. ValueError: attempted relative import beyond top-level package You can not import outside your current package unless it is added in sys.path or PYTHONPATH.
Hmmm. Now it says "ModuleNotFoundError: No module named 'MyProject'" I do have a init.py under the root of MyProject folder
Turns out to be a problem with spyder
0

If you are using any IDE (eg. pycharm) you need to set (my project) as source boot directory else you need to check your BASE_DIR in settings.py

and then you will be able to import the model.

from models.Encoder import BiDirectionalEncoder

and yes if you want to access module from other environment below is the link for ways of accessing and sharing modules.

python module:- importing(accessing) creating and sharing

hope this will resolve your issue.

1 Comment

I dont want to force paths as I mentioned in my question. Esp when I deploy the code in some other environment or machine

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.