I have a class that can interface with either Oracle or MySQL. The class is initialized with a keyword of either “Oracle” or “MySQL” and a few other parameters that are standard for both database types (what to print, whether or not to stop on an exception, etc.).
It was easy enough to add if Oracle do A, elif MySQL do B as necessary when I began, but as I add more specialized code that only applies to one database type, this is becoming ugly. I’ve split the class into two, one for Oracle and one for MySQL, with some shared functions to avoid duplicate code.
What is the most Pythonic way to handle calling these new classes? Do I create a wrapper function/class that uses this same keyword and returns the correct class? Do I change all of my code that calls the old generic class to call the correct DB-specific class?
I’ll gladly mock up some example code if needed, but I didn’t think it was necessary. Thanks in advance for any help!
That’s the idea. Such a function is called a factory function:
Make sure that both database classes have the same API. You can achieve this either with duck typing or with abstract base classes (ABCs); the latter are mostly useful if functionality is shared between the classes, or if you want to do
isinstancechecks to find out if an object represents a database connection.In the case of shared functionality, the template method pattern often comes in handy.