ImportError: cannot import name 'app' from 'mypackage' (unknown location)

Question:

I know that there are a low of similar issues, but none helped me, so I am writing a new one. Here is my directory structure:

- mypackage
    - __init__.py
- run.py
- requirements.txt

The run.py content:

from mypackage import app

app.run(host='localhost', port=3648)

The mypackage/_init_.py content:

from flask import Flask

app = Flask(__name__)

And here is the full error:

C:...parser>python run.py
Traceback (most recent call last):
  File "run.py", line 1, in <module>
    from mypackage import app
ImportError: cannot import name 'app' from 'mypackage' (unknown location)

It seems to be a bug or I am doing something wrong..

UPDATE:
Environment check for PYTHONPATH:

Traceback (most recent call last):
  File "run.py", line 6, in <module>
    print(os.environ['PYTHONPATH'])
  File "C:UserswhiteAppDataLocalProgramsPythonPython37libos.py", line 678, in __getitem__
    raise KeyError(key) from None
KeyError: 'PYTHONPATH'
Asked By: Andrii H.

||

Answers:

I guess when you are running run.py, the current aka working directory is not where that file is. So mypackage is not on sys.path.

Answered By: ivan_pozdeev

i faced the same problem.
i renamed a few files from init.py to ‘__init__.py

Answered By: prashant jeena

Happened to me when Pipenv virtual environment was somehow broken. Deleted the virtualenv and let Pipenv make a new one.

And it worked again.

Answered By: PunchyRascal

tl;dr: rename your package

Was your package really named mypackage? I guess not. 🙂

I had had the same error. In my case, the name I chose for mypackage happened to be the name of an existing Python library I didn’t know about.
Once I renamed my package, the error disappeared.

Answered By: jciloa

One answer that I don’t see here is that Python doesn’t recognize modules if they’re not suffixed with .py. In my case, it turned out that the module in question wasn’t properly suffixed. If you get this error, check if all of your module files are correctly named.

Answered By: Alex.L

keep one init.py file inside the folder. Then it will import as a Module else it will give same error as unknown location

Answered By: Dheeraj Dashora

To me this happened when installing a local version of a pip package which I wanted to debug. The package was named mypackage the same as the folder of which I cloned it via git. You would think that this is not an issue, as it is the default git behavior. But pip confuses this, if the folder name and the package name is the same. I renamed the local git clone to mypackage_git.

Afterwards I installed via

mv mypackage mypackage_git
cd mypackage_git
pip -e .
Answered By: NicoHood
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.