import modules on a first-level directory
In Python, import module goes to Sys.path Search, Sys.path is a list, and we can modify it dynamically.
To import a directory of module, we Sys.path.insert (0,somedir) to join the search path, you can import.
In this case, to import the module on the top-level directory, you can Sys.path.insert (0,parentdir).
But this way of writing an absolute path, if the file is placed elsewhere, it is not.
So use dynamic methods to get to the top level of the directory.
Import Os,sys Parentdir = Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__))) Sys.path.insert (0,parentdir)
Why use Sys.path.insert (0,parentdir) instead of Sys.path.append (Parentdir)?
Because it is traversing the search path, if there is a module with the same name in the other path, the import is wrong. Use Sys.path.insert (0,parentdir) to ensure that the path is searched first.
Solve the problem of circular import
In Python, you often encounter the issue of circular import, which is circular import.
This comical situation is often seen in reality,
When installing the wireless card, you need to download the network card driver.
When installing the compression software, the compression software installation program downloaded from the Internet is actually compressed.
Circular dependencies are similar to this scenario.
Give me a chestnut,
In the models.py,
From server Import DB Class User (db). Model): Pass
In the server.py,
From flask import flask from flask.ext.sqlalchemy import sqlalchemy app = Flask (__name__) app.config[' Sqlalchemy_database _uri '] = ' sqlite:////tmp/test.db ' db = SQLAlchemy (APP) from models import User
This creates the issue of circular import.
There are several main ways to solve the cyclic import.
1. Deferred import (lazy imports)
That is, the import statement is written in the method or function, and its scope is limited to local.
The disadvantage of this approach is that there is a performance problem.
2. Change from XXX import yyy to import xxx;xxx.yyy to access the form
3. Organization Code
The issue of circular import often means that there is a problem with the layout of the code.
You can merge or separate competing resources.
Merging is all written into a file.
The separation is to extract the required import resources to a third-party file.
In short, turn loops into unidirectional.