General import operation for similar classes

In my application, I have a folder / package model

.

In this model folder, I usually have a whole bunch of import statements (most of them are from SQLAlchemy, for example String, Integer, Session

, etc.

I find myself writing the same import operations over and over for things like this User, Blog, Article, Etc.

and got pretty messy.

Understanding that explicit is better than implicit and then go ahead and ignore it, is there a way to do this once?

+3


source to share


2 answers


this is probably not what you want, but who knows

common_imports.py

 from sqlalchemy import Model,String,...

      

in other scripts just

from common_imports import *

      

[edit] actually I came up with a really horrible and hackish way to do what you want

a really hackish way to do this could 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

      

+4


source


I am doing this in one of my applications.

# approot/m.py

from models.model import String, Integer, Session, (etc)

# Otherwise blank!

      

Then, for everything else:

import m

      



Then you can make m.String

, m.Integer

, m.Session

etc. This also means that I can still encapsulate my code so that later when I write custom models I can just add tom.py

from models.user import User, Group, PermissionSet

      

and continue to access m.User

, m.Group

etc.

+4


source







All Articles