Search code examples
pythonflaskimportpython-import

Importing variable from package __init__ in python


I have a project structure as follows:

/src
    __init__.py
manage.py

In __init__.py, I have a variable app declared as app = Flask(__name__).

When trying to import the variable app into manage.py using from src import app, I get the error ImportError: cannot import name 'app' from 'src' (unknown location).

Reading other posts, it seems a common consensus is to use from . import app, which yields ImportError: attempted relative import with no known parent package.

How can I solve this?

EDIT: I keep being asked for the __init__.py file. Here are the full contents of both files:

# src/__init__.py
from flask import Flask

app = Flask(__name__)
# manage.py
from src import app

The traceback for the error is as follows:

Traceback (most recent call last):
  File "---\Project\manage.py", line 1, in <module>
    from src import app
ImportError: cannot import name 'app' from 'src' (unknown location)

FINAL EDIT: It works now. No clue why; nothing has changed but it suddenly works. Cool.


Solution

  • you can just import like that :

    from src import app
    

    but don't forget set before your from .src import * in your __init__.py

    .
    ├── src
    │   └── __init.py__
    └── manage.py
    

    src/__init__.py

    test_var = 5
    

    manage.py

    from src import test_var
    print(test_var)
    

    test

    python3 manage.py
    5