I have a python module that I’ve been using over the years to process a series of text files for work. I now have a need to store some of the info in a db (using SQLAlchemy), but I would still like the flexibility of using the module without db support, i.e. not have to actually have sqlalchemy import’ed (or installed). As of right now, I have the following… and I’ve been creating Product or DBProduct, etc depending on wether I intend to use a db or not.
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Product(object):
pass
class WebSession(Product):
pass
class Malware(WebSession):
pass
class DBProduct(Product, Base):
pass
class DBWebSession(WebSession, DBProduct):
pass
class DBMalware(Malware, DBWebSession):
pass
However, I feel that there has got to be an easier/cleaner way to do this. I feel that I’m creating an inheritance mess and potential problems down the road. Ideally, I’d like to create a single class of Product, WebSession, etc (maybe using decorators) that contains the information neccessary for using a db, but it’s only enabled/functional after calling something like enable_db_support(). Once that function is called, then regardless of what object I create, itself (and all the objects it inherits) enable all the column
bindings, etc. I should also note that if I somehow figure out how to include Product and DBProduct in one class, I sometimes need 2 versions of the same function: 1 which is called if db support is enabled and 1 if it’s not. I’ve also considered “recreating” the object hierarchy when enable_db_support() is called, however that turned out to be a nightmare as well.
Any help is appreciated.
Well, you can probably get away with creating a pure non-DB aware model by using Classical Mapping without using a
declarativeextension. In this case, however, you will not be able to userelationshipsas they are used in SA, but for simple data import/export types of models this should suffice:Another option would be to have a base class for your models defined in some other module and
configureon start-up this base class to be either DB-aware or not, and in case of DB-aware version add additional features like relationships and engine configurations…