I fully acknowledge that Python and Java are different programming languages and should be used differently. That said, “Program to an interface, not to an implementation” is good language-agnostic programming advice.
Say I have some DAO interface in Java:
public interface DataDao {
Object load();
void update();
void delete();
}
Programming to that interface allows me to persist data in files while I’m prototyping, swap that out for a database as I get further along, etc. rather painlessly as long as I honor the contract of the DataDao
.
What’s the Pythonic approach/version (if any) to programming to a contract to keep your classes orthogonal, modular, and enable frictionless implementation changes?
4
You can use abstract base classes, if you really want to. Another option would be to use the mock library while developing and especially while testing.
An abstract base class is like a mix of a Java interface with a Java abstract class: it cannot be instantiated directly, subclasses need to implement all of its methods, but the parent methods may have an implementation that is callable via super
.
Here is an example for an abstract DAO, with concrete file-backed and database-backed subclasses:
import abc
class DataAccess(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def load(self):
pass
@abc.abstractmethod
def update(self):
pass
@abc.abstractmethod
def delete(self):
pass
class FileDataAccess(DataAccess):
def load(self):
with open(self.filename, 'r') as infile:
contents = infile.read()
return contents
def update(self):
pass
def delete(self):
pass
class DbDataAccess(DataAccess):
def load(self):
pass
def update(self):
pass
def delete(self):
pass