Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError: cannot import name

Tags:

python

flask

I have two files app.py and mod_login.py

app.py

from flask import Flask from mod_login import mod_login  app = Flask(__name__) app.config.update(     USERNAME='admin',     PASSWORD='default' ) 

mod_login.py

# coding: utf8  from flask import Blueprint, render_template, redirect, session, url_for, request from functools import wraps from app import app  mod_login = Blueprint('mod_login', __name__, template_folder='templates') 

And python return this error:

Traceback (most recent call last):   File "app.py", line 2, in <module>     from mod_login import mod_login   File "mod_login.py", line 5, in <module>     from app import app   File "app.py", line 2, in <module>     from mod_login import mod_login ImportError: cannot import name mod_login 

If I delete from app import app, code will be work, but how I can get access to app.config?

like image 640
Patrick Burns Avatar asked Jul 24 '13 21:07

Patrick Burns


People also ask

How do I fix the ImportError in python?

Python's ImportError ( ModuleNotFoundError ) indicates that you tried to import a module that Python doesn't find. It can usually be eliminated by adding a file named __init__.py to the directory and then adding this directory to $PYTHONPATH .

What is python import error?

The ImportError is raised when an import statement has trouble successfully importing the specified module. Typically, such a problem is due to an invalid or incorrect path, which will raise a ModuleNotFoundError in Python 3.6 and newer versions.

What is __ init __ py for?

The __init__.py file makes Python treat directories containing it as modules. Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.


2 Answers

The problem is that you have a circular import: in app.py

from mod_login import mod_login 

in mod_login.py

from app import app 

This is not permitted in Python. See Circular import dependency in Python for more info. In short, the solution are

  • either gather everything in one big file
  • delay one of the import using local import
like image 167
hivert Avatar answered Oct 13 '22 00:10

hivert


This can also happen if you've been working on your scripts and functions and have been moving them around (i.e. changed the location of the definition) which could have accidentally created a looping reference.

You may find that the situation is solved if you just reset the iPython kernal to clear any old assignments:

%reset 

or menu->restart terminal

like image 42
mjp Avatar answered Oct 13 '22 01:10

mjp