I recommend composition over inheritance: properly-done composition is superior to inheritance, and code is much more often read than written. I advise avoiding subclassing in general, not using subclassing for code sharing, and remembering that sometimes a function is all you need.
I recommend 99 Bottles of OOP by Sandi Metz: the best intro to OOP design that I’m aware of is 99 Bottles of OOP.
The repository pattern’s purpose is a class that allows you to add and retrieve objects to and from a data store. In this example the repository must also remember added or retrieved objects in a field called seen.
The example needs to keep the actual storage pluggable: use a database like Postgres in production; a dictionary in unit tests. The shared tracking behavior motivates the design question of how to reuse behavior without putting it in a subclass.
The original template-method design has 3 steps: instantiate a subclass, call methods on the base class, and have the base class call methods on the subclass. Its subclasses must implement _add_product and _get_by_sku.
The template-method approach mixes interface definition and code sharing: it mixes the definition of an interface and shares code with the subclass. I find that indirections that go to and fro across class hierarchies are tedious to follow when trying to understand program flow, and the public API is defined by the abstract base class – not the class you’ve actually instantiated!
I describe two alternatives to subclassing: wrap the class by storing it in an instance attribute and delegating to it, or parameterize behavior when you need to customize the behavior of a class across multiple axes.
For the repository case, we only want to do what a concrete repository is doing plus something else, so I choose wrapping rather than behavior parameterization. The example defines a Repository protocol for add_product and get_by_sku; if you don’t use type annotations, you can leave this step out.
DictRepository stores products by SKU using self._storage[product.sku] and retrieves them with self._storage.get(sku). It also doesn’t have to know that a protocol called Repository even exists; a type checker can recognize that it implements the required methods.
TrackingRepository wraps a repository and keeps a seen set. Its add operation delegates to storage and records the product with self._repo.add_product(product) followed by self.seen.add(product); retrieval records a truthy result using if product: self.seen.add(product) return product.
The wrapper’s field is typed _repo: Repository. If you use anything on the _repo attribute that is not promised by the Repository interface, your type checker will yell at you without having to execute the code.
The composition example has two small, independent classes. Its cost is an extra _repo attribute and writing call self._repo.add_product() instead of self._add_product(); I accept that extra typing for clearer method origins and control flow.
I find the composed design easy to read and comprehend , but also easy to test. Its explicit contract makes the classes independent, and better OOP design can help make testing practical beyond simple string manipulation or arithmetic.
I note that formal interfaces are not required; Python is dynamically typed and annotations are strictly optional.
I find that interfaces checked by type checkers such as Mypy have become verified API documentation.
I describe abstract base classes as using nominal subtyping; Python 2.6 is when they first appeared.
I note that, for abstract base classes, The distinction is not always 100% clear.
I note that protocols arrived in Python 3.8; typing-extensions back to Python 3.5 makes them available earlier.
I prefer small interfaces: the smaller an interface, the better.
I argue that Code sharing via subclassing is a bad idea. Multiple inheritance makes it an extra bad idea.
I have seen good uses of this pattern, but you have to be very judicious with your approach.
I give the MailSender example: it sends an email in production but just prints it to the console in development.
I describe abstract data types as mainly serving to tighten interface contracts.
I want an interface to specify an object’s required properties while leaving its other properties irrelevant.
I chose the term “interfaces” because it sounds “a lot less pretentious.”
I explain that printer() only needs read() to return a string it can print, whether that result comes from a predefined string, a file, or a web API call.
I note that a type checker will object if printer() calls a method other than read() on its argument.
I describe ABCs as a less powerful version of zope.interface that uses nominal subtyping.
I note that some abstract base classes are incomplete classes intended to be completed by subclassing and implementing their abstract methods, rather than interfaces.
I describe protocols as avoiding subclassing through structural subtyping.
I say nominal and structural subtyping are straightforward to explain.
I show that both FooReader and BarReader pass isinstance(..., Reader) in the nominal example.
I note that registering a class gives the freedom to use more dynamic or “magical” means to provide the desired interface.
I note that using register() as a class decorator can save two empty lines.
I note that subclassing an ABC can smuggle in code sharing by adding regular methods to the abstract base class.
I acknowledge that code sharing through ABC methods can be a good trade-off within Python’s constraints and culture, although it is not great for the reasons discussed.
I note that FooReader does not know the Reader protocol exists.
I find protocols useful when different implementations of the same interface exist in one code base.
I find protocols useful for explicitly documenting the small subset of a third-party class that I use.
I describe protocols as verified documentation that helps when implementing fakes for tests.
I open this discussion with Tim Peters’s principle: “Namespaces are one honking great idea – let’s do more of those!”
I consider most criticism of subclassing for code sharing justified.
I say I rely on exceptional prior art, including Brandon Rhodes’s “The Composition Over Inheritance Principle,” rather than adding much to the discussion myself.
I note that Python’s double-underscore prefix, __x, addresses the naming-conflict scenario, but that practice has been frowned upon in favor of the principle of consenting adults.
I warn that subclassing makes unrelated classes share a namespace: “You’re relying on classes – that you potentially don’t control and that know nothing about each other – getting along in a shared namespace.”
I point to attrs and, ultimately, dataclasses choosing class decorators instead of subclassing so that attaching things to a class is deliberate and does not accidentally leak them to subclasses.
I describe confusing indirections as a special case of the namespace problem and the main point of Augie Fackler and Nathaniel Manista’s talk.
I note that the Stack Overflow question “what is super() even for?” had almost 3,000 upvotes and more than 1,000 bookmarks.
I consider APIs that require subclassing to implement or overwrite methods called elsewhere especially problematic.
I quote Cory Benfield: “‘Also the subclassing based design was a huge mistake’ is probably the most-commonly uttered sentence in programming.”
I hold that If you want to customize more than one behavioral aspect of a class, code sharing via subclassing won’t work; it leads to subclass explosion.
I note that It takes research and mental energy to find out where x is coming from; this is true while reading code and debugging.
I warn that two classes in the same hierarchy that don’t know about each other may try to have an attribute with the same name.
I argue that informed consent is impossible if all parties aren’t informed; this problem gets exponentially worse with multiple inheritance and mixins.
I point out that you have no control over the methods and attributes that you expose from the base classes to your users; they can tarnish your API surface and change over time.
I note that class decorators make attachment deliberate and make it impossible to accidentally leak something to all subclasses.
I explain that If every method is on self, it’s unclear where it’s coming from when looking at the call; attempts to understand control flow can end in a wild goose chase.
I advise that Once multiple inheritance comes into play, understand the MRO and super().
I say that Twisted and asyncio committed these sins in their Protocol classes; it scarred me forever.
I note that it’s complicated to find out which methods exist, especially in deep hierarchies; a subtly wrong method name can fail silently.
I use subclassing for code sharing only if I need to bend the behavior of a class that I don’t control; I consider it a less egregious type of monkey patching.
I generally recommend that Usually it’s better to write an Adapter, Facade, Proxy, or Decorator; delegation can be cumbersome when many methods must be forwarded to change a small detail.
My recommendation is don’t make subclassing a central part of your design.
I cite Augie Fackler and Nathaniel Manista’s talk, The End Of Object Inheritance & The Beginning Of A New Modularity at PyCon US 2013.
I cite Sandi Metz’s talk, Nothing is Something at RailsConf 2015.
In my article “Subclassing in Python Redux,” I examine when subclassing is a pragmatic choice in Python, despite my general preference for composition. I begin by distinguishing different kinds of inheritance before judging subclassing as a whole.
I define specialization this way: “if we say that a class B specializes base class A we say that class B is A with additional properties.”
I warn that “a square is not a rectangle plus more”; a square is not necessarily a valid specialization of a rectangle.
I say that code must be able to interact with a square as an instance of its base class without needing to know it is a square; otherwise, it violates the Liskov substitution principle and prevents polymorphic code.
I find specialization useful for data that is strictly hierarchical. My email-account example distinguishes mailboxes, which store messages on the server and need password-hash login information, from forwarding-only accounts, which accept email and forward it elsewhere. These added fields and methods change little to nothing about the shared information and behavior.
For the simple email-account model, I recommend “create a dedicated class for each case”; I advise against deduplication unless there are many more fields and types, because “duplication is far cheaper than the wrong abstraction.”
class Mailbox:
id: UUID
addr: str
pwd: str
class Forwarder:
id: UUID
addr: str
targets: list[str]
Mailbox | Forwarder
I assess the single-class optional-field design as “more DRY” technically, but its usage is awkward, its fields’ existence and types depend on the type field, and a type checker cannot sensibly check it.
I say that grouping the behavior on one optional-field class leads to conditions that increase code complexity, while “The whole point of polymorphism is to avoid that.”
I describe optional attributes as “potentially a red flag” and fields needing comments to explain when to use them as a “May Day Rally.”
I assess composition as “not that bad”: it has no optional fields and its data relationships are clear, but it is clunky because EmailAddr and Mailbox / Forwarder are “too closely related.”
I conclude that the models’ shared base information and close relationship point toward specialization by subclassing; I will return to composition when improving a subclassing-based design.
class EmailAddr:
id: UUID
addr: str
class Mailbox(EmailAddr):
pwd: str
class Forwarder(EmailAddr):
targets: list[str]
I consider the shared-base design the most ergonomic, DRY, obvious, and feasible to type check. “A Mailbox strictly is an EmailAddr plus more,” and both users and type checkers know it has a pwd field.
I say subclassing requires knowledge and discipline, whereas “Composition mechanically forces discipline”; composition can leave less room for human error even when it is clunky.
I advise keeping related subclass definitions physically close and not overdoing subclassing, since readers otherwise have to assemble the final class in their heads to know its fields.
My general advice is to “always focus on the shape of your data first and only then what to do with it”; once the shape is settled, behavior comes more naturally.
I advise asking whether a function would be enough, especially when coordinating work across classes without polymorphism; if it is unclear what class owns a method, the answer is often “neither.”
I have used this approach in my parsing library for PEM files and “have yet to regret it.”
My heuristic is to use subclassing when I “could” – and “would”! – use embedding in Go.
I describe Go embedding as a pragmatic compromise: a Mailbox instance can have an addr attribute as if defined directly on it, but there is no actual hierarchy or super(), and calls can only go sideways.
I recommend learning about @singledispatch; it “will feel like magic if you haven’t yet.” Following these guidelines gives objects excellent testability.
I note that this kind of inheritance is unavoidable in Python unless I stop using Exceptions.
I see interfaces as a special case of specialization: they specialize a generic API contract into something concrete.
class AddrType(enum.Enum):
MAILBOX = "mailbox"
FORWARDER = "forwarder"
class EmailAddr:
type: AddrType
id: UUID
addr: str
pwd: str | None
target: list[str] | None
I warn that fields needing a comment to explain when to use them are a “May Day Rally.”
I say type annotations can clearly point out a problem with a model that might otherwise be harder to notice because code complexity is not as straightforward to recognize.
I describe a less painful optional-field variant: move mailbox-specific data into its own class and make just that field optional; I consider it better but still unnecessarily clunky.
I say composition itself is not failing us; in this email-account model, forcing an “has-a” relationship feels like going against the grain.
I use Sans I/O as an unequivocally data-first example because behavior is supposed to be replaceable by design.
I advise avoiding cross-hierarchy interactions between methods while specializing.
I say that following these guidelines gives objects excellent testability.
I am firmly in the composition-over-inheritance camp, but I also believe Python is designed in a way that you can’t write idiomatic code without subclassing sometimes.
I describe this as the longest piece of prose I had written since my thesis in 2006.
I considered splitting the article into at least three parts, but chose to keep it as a standalone piece because I wanted it to be a distilled essence of what I’ve learned over the years.
I argue that there are three types that should never be mixed; when kept separate, one is good, one is optional but useful, and one is bad.
I attribute most subclassing problems to trying to use more than one type of subclassing at once, or to focusing object design on the bad type.
I frame subclassing as a trade-off: in all cases, you sacrifice reading convenience for writing convenience, and that trade-off can be worthwhile in some instances.
I point to Go and Rust as examples of languages showing that you don’t need subclassing to successfully write code.
I link the article to its Chinese translation, “再谈 Python 中的继承.”
I reference “Why inheritance never made any sense” for its framework of three inheritance types. This excerpt introduces the framework and says I will start with the bad type, but it does not yet name or explain the types. The practical question of when subclassing is appropriate in Python remains open here.
I close the article by thanking readers and explaining that my goal is to add nuance to the discussion. I invite readers to share the article, offer feedback, and get in touch about presentations based on the talk. The article’s length may limit casual sharing, but I hope its URL can help readers disengage from heated public discussions.
My argument is that using Exceptions doesn’t make it a good idea to also use the template method pattern, because “ both are subclassing ”.
My ultimate goal is to add more nuance to the discussion.
Due to its length, this article is unlikely to get a lot of “ see, read, retweet / upvote ” sharing.
I encourage readers to share the article in any way to help it spread.
I invite readers to let me know what they think about the article or how many coffees it took them to get through.
The linked article may be difficult to understand if its vernacular is unfamiliar, but readers do not need to read it to understand my blog post; reading my post may make the linked article easier to understand.
I note that this concept is completely unrelated to typing.Protocol, which I discuss later.
I name Twisted because I was part of its core team when we recognized our errors; it is an acknowledged error, not shade.
I note that this concept is also called “implementing a protocol,” and that searching Python documentation for “protocol” yields an eclectic collection of results.
The L in SOLID refers to the L in SOLID.
I’m keeping the example short for brevity; it would not make sense to make such a big deal for two types with two fields each.
Nullable attributes or fields are fields that can be None.
Readers can find the referenced discussion by searching for ‘Does it “make you want to beat Harry around the head with a plushie snake”?’
The book is available to read for free on the web, and I encourage readers with a book budget to support Harry and Bob because I want them rewarded for writing it.
I’m not getting any commission for the book; I get the recognition of having my name on the back cover next to Brandon Rhodes’s.
For our discussion, the shape of Product is not interesting except that it has an sku field of type str.
I describe myself as a Code Bohemian in love with Python, Go, and DevOps.
I am a blogger, speaker, YouTuber, and PSF fellow, and I value substance over flash.
I’m explicitly not going to talk about standard library APIs. Yes, SimpleHTTPServer requires you to subclass, but that’s an API decision and not inherent to Python’s design.
I don’t plan on spending much time on public discussions, because they tend to get too heated, pedantic, and dogmatic. I wrote the article in part so I can point people to its URL and disengage.
In the square-and-rectangle example, code written for rectangles assumes width and height can be manipulated independently; a square must silently change the other dimension or raise an error.
I note that Exceptions commonly carry subtype-identifying information such as ValueError without adding methods, attributes, or behaviors.
I would argue that the class is too big if it comes so far; I’m usually only doing it to classes that I don’t control.
I clarify that Technically, this is the original Decorator Pattern. We maintain the API and add behavior.
I also explain that the linked article is optional for understanding my post, though my post may make it easier to understand. I name Twisted to acknowledge an error I was part of recognizing as a core-team member, not to criticize the project. Other footnotes identify the L in SOLID, define nullable fields as attributes or fields that can be None, and explain that one example is shortened for brevity.
I recommend supporting Harry and Bob’s book if readers have a book budget; it is available free on the web, and I receive no commission. The article’s closing also credits donations and offers my free, low-volume “Hynek Did Something” newsletter for direct content and additional context. I describe myself as working with Python, Go, and DevOps, and as a blogger, speaker, YouTuber, PSF fellow, and advocate of substance over flash.
I see the conflict between subclassing and composition as old as object-oriented programming.
My goal in the article is to meditate on when Python’s “sometimes” calls for subclassing and to untangle my gut feelings on the topic.
I think discussions of subclassing can be frustratingly fruitless because there isn’t just one type of inheritance.
I value concise, practical software-design guidance and clear ways to express engineering intuitions. My views on Kent Beck’s Tidy First?, domain-driven design, and architecture terminology reflect that preference.
I am neither a fan of “Clean Code” nor of “A Philosophy of Software Design,” but I have come to really like Kent Beck’s “Tidy First?”.
I like that Tidy First? doesn’t try to be an all-encompassing tome.
I value Tidy First? for its easily digestible hyper-local advice.
Guard clauses are one example of the hyper-local advice in Tidy First?.
I haven’t really learned anything from reading its ~100 pages.
I consider Tidy First? a great resource for beginners & intermediates who want to improve their craft.
I value Evans’s advice to “constrain relationships [btw objects] as much as possible.”
I understand a bidirectional association to mean that both objects can be understood only together.
I find DDD an amazing source for putting my SWE gut feelings into catchy and sticky words.
I think software architecture would be so much easier to talk about if all key terms weren’t random combinations of “model”, “event”, “domain”, and “service”.
I describe vertical slice architecture as turning a massive system into smaller pieces that are easier to manage, with some slices becoming polished without a grand refactoring.
I think vertical slice architecture gives you cohesion and boundaries, which are Very Good Things™ for understanding and isolated changes.
I call the linked book the best book on OOP I know, and I’m glad it is now available for Python, too.
I find the Python in the translation not very idiomatic, as I expected, but it removes friction to understand what the book is teaching.
I think criticizing OOP for subclassing crimes is a strawman argument.
I complain that every cthulhudamned OOP tutorial starts with subclassing some bloody kind of vehicle.