Splitting SQLAlchemy mapping class from functional class in python

I'm sure there have been questions about this before, and I'm just not looking for relevant keywords ...

Is it good / bad practice to separate the ORM mapping classes from the classes that are used for processing in the application?

For example:

class Artist:
    def __init__(self, name, age, genre):
        self.name  = name
        self.age   = age
        self.genre = genre
        self.score = None # Calculated in real-time, never stored to DB

class ArtistM(Base):
    __tablename__ = "artists"
    name          = Column(String(50))
    age           = Column(Integer)
    genre         = Column(String(50))

      

The intended benefit would be that the classes used by the main application are completely free of ORM stuff. For example, suppose I created an Artist class and a whole set of tools that work with that class. Later, I want to start processing LOTS of these objects and decide to add a DB component. Should I go back and modify the original Artist class or create new mapping classes from above?

+3


source to share


1 answer


Use inheritance for this:

# Option-1: use ArtistM everywhere
class ArtistM(Artist, Base):
    # ...

# Option-2: use Artist everywhere
class Artist(ArtistM):
    # ...

      



I prefer option 1 as it doesn't bloat your clean classes with persistent related information. And in your code, you could even import them with clean names so that you can use your other code interchangeably:

from mypuremodule import Artist
# or
from mymixedinmodule import ArtistM as Artist
# then use 'Artist` everywhere

      

0


source







All Articles