Reputation: 8596
In my app, I have a model
folder / package.
In that model folder, I generally have a whole bunch of import statements (most of them from SQLAlchemy, such as String, Integer, Session
, etc.
I find myself writing the same import statements again and again for stuff like User, Blog, Article, Etc.
and have become pretty sloppy at it.
Understanding that explicit is better than implicit and then going ahead and disregarding that, is there a way to do this once?
Upvotes: 3
Views: 70
Reputation: 113988
this probably isnt what you want but who knows
from sqlalchemy import Model,String,...
in other scripts just do
from common_imports import *
[edit] actually I came up with a really awful and hacky way to do what you want
a really hacky way to do it might be something like
\root_of_package
-main.py
\models
-__init__.py
-model1.py
-model2.py
then in models\__init__.py
from sqlalchemy import String,Integer,...
from glob import glob
Base = ...
for fname in glob("%s/*.py"%dirname(__file__)):
with open(fname) as f:
eval(f.read())
__all__ = locals()
then in models/model1.py
#just use all the imports/locals from __init__.py as if they already existed
#this will be hellish if you use an IDE that checks for errors for you
class Model1(Base):
id = Column(Integer,primary_key=True)
...
then in main.py
from models import Model1
Upvotes: 4
Reputation: 54213
I do this in one of my applications.
# approot/m.py
from models.model import String, Integer, Session, (etc)
# Otherwise blank!
Then in everything else:
import m
Then you can do m.String
, m.Integer
, m.Session
and etc. This also means I can further encapsulate my code so that later when I write up user models I can just add to m.py
from models.user import User, Group, PermissionSet
and continue to access m.User
, m.Group
and etc.
Upvotes: 4