While programming under eclipse+PyDev and using Flask framework, I noticed that the auto-organizing imports feature from IDE (invoked with Ctrl+O) sometimes gets in the way.
This is related to the way Flask deals with the need of splitting views code into multiple modules, or packages. Basically, if you have a views.py module that contains your request handlers:
from myapp import app
@app.route('/')
def root():
return "Hello world"
and your Flask app is defined in __init__.py:
from flask import Flask
app = Flask('MyApp')
app.config.from_pyfile('config.py')
@app.before_request
def before_request(): pass # omitted for brevity
@app.teardown_request
def teardown_request(): pass # omitted for brevity
you need to import views at the end of the latter file for the view functions to be added to Flask’s routing table. Since views.py imports __init__.py to access the app variable, this results in circular import. It works fine, though, and is in fact an established practice, as suggested by documentation.
Unfortunately, PyDev knows nothing about this technique. Should we accidentally trigger organizing imports for __init__.py (not uncommon, given how useful this option is in general), PyDev will happily move the crucial import views to the top. Of course, this results in incorrect (irresolvable) circular import, and an annoying runtime error.
Is there a way to prevent this from happening – like a #@Directive that would tell PyDev to leave this specific import alone, a way to turn off import organizing on per-file basis, or something similar?
I don’t use PyDev, but have you tried throwing off its import parser? This is dirty, but you could try something like:
Since the line doesn’t begin with “import”, maybe PyDev will pass it over?