Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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:\Users\white\AppData\Local\Programs\Python\Python37\lib\os.py", line 678, in __getitem__
    raise KeyError(key) from None
KeyError: 'PYTHONPATH'
like image 266
Andrii H. Avatar asked Apr 12 '19 17:04

Andrii H.


Video Answer


2 Answers

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.

like image 58
jciloa Avatar answered Oct 11 '22 16:10

jciloa


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.

like image 43
ivan_pozdeev Avatar answered Oct 11 '22 17:10

ivan_pozdeev