{"course":{"slug":"python-for-ai","title":"Python, from Zero, for AI","url":"https://addaly.com/learn/python-for-ai","level":"beginner","track":"build"},"lesson":{"slug":"inheritance-and-composition","title":"Inheritance and composition: swapping one model provider for another","url":"https://addaly.com/learn/python-for-ai/inheritance-and-composition","position":62,"of":89,"minutes":9,"answer":"Put the one thing that differs between providers behind a small base class with a single method.","keyIdea":"Put the one thing that differs between providers behind a small base class with a single method, and give the rest of the program an object that has a provider rather than is one: inheritance for the interface, composition for everything else."},"body":{"format":"markdown","text":"## The problem it solves\n\nModule 6 left you with a piece of advice: keep the model call in one function so that switching providers changes one place. Here is the shape that advice grows into when a program is large enough to need it.\n\nYour program wants to say \"ask the model this\" and get text back. It does not want to know whether the model is Anthropic's, OpenAI's, or a free one running under Ollama. Those differ in URL, headers, request shape and response shape, and in nothing that the rest of the program cares about.\n\n## A base class that states the interface\n\n```python\nimport anthropic  # pip install anthropic\nimport openai     # pip install openai\n\nclass ChatProvider:\n    def complete(self, messages, max_tokens=1024):\n        raise NotImplementedError\n\nclass AnthropicProvider(ChatProvider):\n    def __init__(self, model):\n        self.client = anthropic.Anthropic()\n        self.model = model\n\n    def complete(self, messages, max_tokens=1024):\n        system = next(\n            (\n                m[\"content\"]\n                for m in messages\n                if m[\"role\"] == \"system\"\n            ),\n            None,\n        )\n        rest = [\n            m for m in messages if m[\"role\"] != \"system\"\n        ]\n        request = {\n            \"model\": self.model,\n            \"max_tokens\": max_tokens,\n            \"messages\": rest,\n        }\n        if system is not None:\n            request[\"system\"] = system\n        r = self.client.messages.create(**request)\n        text = \"\".join(\n            block.text for block in r.content\n            if block.type == \"text\"\n        )\n        if r.stop_reason == \"max_tokens\" or not text:\n            raise RuntimeError(\n                \"No complete text response: \"\n                f\"{r.stop_reason}\"\n            )\n        return text\n\nclass OpenAICompatibleProvider(ChatProvider):\n    def __init__(self, model, base_url=None, api_key=None):\n        self.client = openai.OpenAI(\n            base_url=base_url,\n            api_key=api_key,\n        )\n        self.model = model\n\n    def complete(self, messages, max_tokens=1024):\n        r = self.client.chat.completions.create(\n            model=self.model,\n            messages=messages,\n            max_tokens=max_tokens,\n        )\n        return r.choices[0].message.content\n```\n\n`class AnthropicProvider(ChatProvider)` says: this is a kind of `ChatProvider`. It **inherits** everything the base has and **overrides** `complete` with its own. The base's `complete` raises, so a subclass that forgets to override it fails loudly the first time it is called rather than silently returning `None`.\n\nThe differences (Anthropic wants the system prompt as a separate argument, and returns a list of content blocks) are absorbed inside each subclass. The caller sees one method:\n\n```python\nprovider = OpenAICompatibleProvider(\"qwen2.5:0.5b\", base_url=\"http://localhost:11434/v1\", api_key=\"x\")\nreply = provider.complete([{\"role\": \"user\", \"content\": \"Hi\"}])\n```\n\nSwap the first line and nothing else changes. That is the whole payoff.\n\nFor Anthropic, you can construct `AnthropicProvider(\"claude-sonnet-5-5\")` after setting `ANTHROPIC_API_KEY`. Its response may begin with a thinking block, so the adapter selects text blocks and reports a truncated or empty text response instead of adding it to the conversation. Thinking tokens share the output cap with the answer. The adapter sends a system prompt only when one was supplied. Check the current [Messages API response format](https://platform.claude.com/docs/en/api/messages/create) when updating a provider.\n\n## `super()` and `isinstance`\n\nWhen a subclass needs the parent's version too, `super()` reaches it:\n\n> Figure: One interface, several providers, one object that holds one. Layers, top to bottom: Your program (Asks one thing: assistant.say(question)); Assistant (HAS a provider and HAS a conversation: composition); ChatProvider (One method: complete(messages, system) -> str); AnthropicProvider · OpenAIProvider · OllamaProvider (Inherit the interface, absorb each service's shape); FakeProvider (Returns a canned string, so tests need no network and no money). Inheritance is used once, for the interface, because every provider genuinely can be used wherever a ChatProvider can. Everything else is composition: Assistant has a provider and has a conversation, which is what lets you swap a fake one in a test or fall back to a cheaper model when the budget is nearly spent.\n\n```python\nimport logging\n\nlog = logging.getLogger(__name__)\n\nclass LoggingProvider(OpenAICompatibleProvider):\n    def complete(self, messages, max_tokens=1024):\n        log.info(\"asking %s with %d messages\", self.model, len(messages))\n        return super().complete(messages, max_tokens)\n```\n\n`isinstance(provider, ChatProvider)` is true for every subclass, which is what lets a function accept \"any provider\" and check it got one.\n\n## Where inheritance lies\n\nThe textbook example is a square that inherits from a rectangle. A square is a rectangle, so it must be fine. Then someone calls `set_width(5)` on a square and its height silently changes too, and code written for rectangles is now wrong for one of them.\n\nThe rule that survives contact with real programs: inherit only when the subclass can be used **everywhere** the parent can, with no surprises. That is a much stricter condition than \"shares some code\". Two classes that share code but differ in what they promise should not be parent and child; they should share a helper function or a common base that states only the promise.\n\nIn the example above, `OllamaProvider(OpenAICompatibleProvider)` would be tempting: the request format is the same. But Ollama does not return the cached-token fields, does not enforce `max_tokens` the same way, and has no billing. The day the parent grows a method that assumes one of those, the child breaks. The safer structure is what the example already has: both are siblings under `ChatProvider`, and if two siblings want to share the request-building code, they call the same module-level function.\n\n## Composition: the object that has a provider\n\nThe rest of the program should not inherit from a provider either. It should **hold one**:\n\n```python\nclass Assistant:\n    def __init__(self, provider: ChatProvider, system: str):\n        self.provider = provider\n        self.conversation = Conversation(model=None, system=system)\n\n    def ask(self, text):\n        self.conversation.add(\"user\", text)\n        reply = self.provider.complete(self.conversation.messages)\n        self.conversation.add(\"assistant\", reply)\n        return reply\n```\n\nThe conversation holds message history. Its model argument is `None` here because the provider owns the model choice.\n\n`Assistant` *has a* provider and *has a* conversation. It is not a kind of either. You can hand it a fake provider in a test that returns canned text, a logging wrapper in development, or a real one in production, and `Assistant` is unchanged. This is the same move as module 4's \"hand the call in\", now with an object instead of a function.\n\nComposition also lets you change the provider at runtime (fall back to a cheaper model when the budget is nearly spent) which a subclass fixed at definition time cannot do.\n\n## Duck typing, and when the base class is optional\n\nPython does not require the base class. Any object with a `complete` method that takes those arguments will work in `Assistant`, whether or not it inherits from `ChatProvider`. That is duck typing, and it is why a test can pass in a two-line class. The base class earns its place by documenting the interface in one spot, by giving `isinstance` something to check, and by making a forgotten method raise `NotImplementedError` at the right line. `typing.Protocol`, covered later in this module, gives the same documentation without requiring inheritance at all.\n\n## Try this now\n\nWrite `ChatProvider`, one real subclass against Ollama, and a `FakeProvider` whose `complete` returns `\"ok: \" + messages[-1][\"content\"]`. Build `Assistant` around each and confirm the `Assistant` code does not change. Then try `LoggingProvider` with `super()`."},"check":{"question":"A developer writes `class OllamaChat(OpenAIChat)` because the two providers share a request format, overriding only `base_url`. Later the OpenAI class gains a method that reads `usage.prompt_tokens_details` for cached-token pricing, which Ollama's responses do not include, and every Ollama call now raises `AttributeError`. What went wrong structurally?","options":[{"text":"The subclass should have declared `__slots__` so that attributes missing from the response would default to zero.","correct":false,"tempting":"`__slots__` restricts which attributes an instance can have; it does nothing about missing keys in a response object."},{"text":"Python resolves methods on the parent before the child, so the override of `base_url` was ignored once a new method was added to the parent and the lookup order was recomputed.","correct":false,"tempting":"Method resolution checks the child first; the override worked, and the failure is in a method the child never overrode."},{"text":"The subclass inherited every future assumption of its parent, not just the request shape; two siblings under a one-method base would have stayed separate.","correct":true},{"text":"Subclasses cannot override attributes, only methods, so `base_url` should have been passed to `__init__` instead.","correct":false,"tempting":"Class attributes are overridable in a subclass; the problem is not the override mechanism but what else came along with it."}]},"prev":{"slug":"dataclasses","title":"Dataclasses: the class that is mostly data, written in four lines","url":"https://addaly.com/learn/python-for-ai/dataclasses"},"next":{"slug":"dunder-methods","title":"Dunder methods: making your own objects work with len, for, in and ==","url":"https://addaly.com/learn/python-for-ai/dunder-methods"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Inheritance and composition: swapping one model provider for another', in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/inheritance-and-composition (Accessed: 21 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Inheritance and composition: swapping one model provider for another","courseTitle":"Python, from Zero, for AI","module":{"index":7,"slug":"objects-and-the-shape-of-programs","title":"Objects, generators and the shape a larger program takes"},"answer":null,"keyIdea":"Put the one thing that differs between providers behind a small base class with a single method, and give the rest of the program an object that has a provider rather than is one: inheritance for the interface, composition for everything else.","hero":{"kind":"figure","figure":{"t":"figure","label":"Figure","figure":{"caption":"Inheritance is used once, for the interface, because every provider genuinely can be used wherever a ChatProvider can. Everything else is composition: Assistant has a provider and has a conversation, which is what lets you swap a fake one in a test or fall back to a cheaper model when the budget is nearly spent.","layers":[{"label":"Your program","detail":"Asks one thing: assistant.say(question)"},{"label":"Assistant","detail":"HAS a provider and HAS a conversation: composition"},{"label":"ChatProvider","detail":"One method: complete(messages, system) -> str"},{"label":"AnthropicProvider · OpenAIProvider · OllamaProvider","detail":"Inherit the interface, absorb each service’s shape"},{"label":"FakeProvider","detail":"Returns a canned string, so tests need no network and no money"}],"title":"One interface, several providers, one object that holds one","type":"stack"},"alt":"Figure: One interface, several providers, one object that holds one. Layers, top to bottom: Your program (Asks one thing: assistant.say(question)); Assistant (HAS a provider and HAS a conversation: composition); ChatProvider (One method: complete(messages, system) -> str); AnthropicProvider · OpenAIProvider · OllamaProvider (Inherit the interface, absorb each service’s shape); FakeProvider (Returns a canned string, so tests need no network and no money). Inheritance is used once, for the interface, because every provider genuinely can be used wherever a ChatProvider can. Everything else is composition: Assistant has a provider and has a conversation, which is what lets you swap a fake one in a test or fall back to a cheaper model when the budget is nearly spent."}},"blocks":[{"t":"h2","id":"the-problem-it-solves","runs":[{"text":"The problem it solves"}]},{"t":"p","runs":[{"text":"Module 6 left you with a piece of advice: keep the model call in one function so that switching providers changes one place. Here is the shape that advice grows into when a program is large enough to need it."}]},{"t":"p","runs":[{"text":"Your program wants to say “ask the model this” and get text back. It does not want to know whether the model is Anthropic’s, OpenAI’s, or a free one running under Ollama. Those differ in URL, headers, request shape and response shape, and in nothing that the rest of the program cares about."}]},{"t":"h2","id":"a-base-class-that-states-the-interface","runs":[{"text":"A base class that states the interface"}]},{"t":"code","lang":"python","label":"Python","text":"import anthropic  # pip install anthropic\nimport openai     # pip install openai\n\nclass ChatProvider:\n    def complete(self, messages, max_tokens=1024):\n        raise NotImplementedError\n\nclass AnthropicProvider(ChatProvider):\n    def __init__(self, model):\n        self.client = anthropic.Anthropic()\n        self.model = model\n\n    def complete(self, messages, max_tokens=1024):\n        system = next(\n            (\n                m[\"content\"]\n                for m in messages\n                if m[\"role\"] == \"system\"\n            ),\n            None,\n        )\n        rest = [\n            m for m in messages if m[\"role\"] != \"system\"\n        ]\n        request = {\n            \"model\": self.model,\n            \"max_tokens\": max_tokens,\n            \"messages\": rest,\n        }\n        if system is not None:\n            request[\"system\"] = system\n        r = self.client.messages.create(**request)\n        text = \"\".join(\n            block.text for block in r.content\n            if block.type == \"text\"\n        )\n        if r.stop_reason == \"max_tokens\" or not text:\n            raise RuntimeError(\n                \"No complete text response: \"\n                f\"{r.stop_reason}\"\n            )\n        return text\n\nclass OpenAICompatibleProvider(ChatProvider):\n    def __init__(self, model, base_url=None, api_key=None):\n        self.client = openai.OpenAI(\n            base_url=base_url,\n            api_key=api_key,\n        )\n        self.model = model\n\n    def complete(self, messages, max_tokens=1024):\n        r = self.client.chat.completions.create(\n            model=self.model,\n            messages=messages,\n            max_tokens=max_tokens,\n        )\n        return r.choices[0].message.content"},{"t":"p","runs":[{"text":"class AnthropicProvider(ChatProvider)","code":true},{"text":" says: this is a kind of "},{"text":"ChatProvider","code":true},{"text":". It "},{"text":"inherits","b":true},{"text":" everything the base has and "},{"text":"overrides","b":true},{"text":" "},{"text":"complete","code":true},{"text":" with its own. The base’s "},{"text":"complete","code":true},{"text":" raises, so a subclass that forgets to override it fails loudly the first time it is called rather than silently returning "},{"text":"None","code":true},{"text":"."}]},{"t":"p","runs":[{"text":"The differences (Anthropic wants the system prompt as a separate argument, and returns a list of content blocks) are absorbed inside each subclass. The caller sees one method:"}]},{"t":"code","lang":"python","label":"Python","text":"provider = OpenAICompatibleProvider(\"qwen2.5:0.5b\", base_url=\"http://localhost:11434/v1\", api_key=\"x\")\nreply = provider.complete([{\"role\": \"user\", \"content\": \"Hi\"}])"},{"t":"p","runs":[{"text":"Swap the first line and nothing else changes. That is the whole payoff."}]},{"t":"p","runs":[{"text":"For Anthropic, you can construct "},{"text":"AnthropicProvider(\"claude-sonnet-5-5\")","code":true},{"text":" after setting "},{"text":"ANTHROPIC_API_KEY","code":true},{"text":". Its response may begin with a thinking block, so the adapter selects text blocks and reports a truncated or empty text response instead of adding it to the conversation. Thinking tokens share the output cap with the answer. The adapter sends a system prompt only when one was supplied. Check the current "},{"text":"Messages API response format","href":"https://platform.claude.com/docs/en/api/messages/create"},{"text":" when updating a provider."}]},{"t":"h2","id":"super-and-isinstance","runs":[{"text":"super()","code":true},{"text":" and "},{"text":"isinstance","code":true}]},{"t":"p","runs":[{"text":"When a subclass needs the parent’s version too, "},{"text":"super()","code":true},{"text":" reaches it:"}]},{"t":"code","lang":"python","label":"Python","text":"import logging\n\nlog = logging.getLogger(__name__)\n\nclass LoggingProvider(OpenAICompatibleProvider):\n    def complete(self, messages, max_tokens=1024):\n        log.info(\"asking %s with %d messages\", self.model, len(messages))\n        return super().complete(messages, max_tokens)"},{"t":"p","runs":[{"text":"isinstance(provider, ChatProvider)","code":true},{"text":" is true for every subclass, which is what lets a function accept “any provider” and check it got one."}]},{"t":"h2","id":"where-inheritance-lies","runs":[{"text":"Where inheritance lies"}]},{"t":"p","runs":[{"text":"The textbook example is a square that inherits from a rectangle. A square is a rectangle, so it must be fine. Then someone calls "},{"text":"set_width(5)","code":true},{"text":" on a square and its height silently changes too, and code written for rectangles is now wrong for one of them."}]},{"t":"p","runs":[{"text":"The rule that survives contact with real programs: inherit only when the subclass can be used "},{"text":"everywhere","b":true},{"text":" the parent can, with no surprises. That is a much stricter condition than “shares some code”. Two classes that share code but differ in what they promise should not be parent and child; they should share a helper function or a common base that states only the promise."}]},{"t":"p","runs":[{"text":"In the example above, "},{"text":"OllamaProvider(OpenAICompatibleProvider)","code":true},{"text":" would be tempting: the request format is the same. But Ollama does not return the cached-token fields, does not enforce "},{"text":"max_tokens","code":true},{"text":" the same way, and has no billing. The day the parent grows a method that assumes one of those, the child breaks. The safer structure is what the example already has: both are siblings under "},{"text":"ChatProvider","code":true},{"text":", and if two siblings want to share the request-building code, they call the same module-level function."}]},{"t":"h2","id":"composition-the-object-that-has-a-provider","runs":[{"text":"Composition: the object that has a provider"}]},{"t":"p","runs":[{"text":"The rest of the program should not inherit from a provider either. It should "},{"text":"hold one","b":true},{"text":":"}]},{"t":"code","lang":"python","label":"Python","text":"class Assistant:\n    def __init__(self, provider: ChatProvider, system: str):\n        self.provider = provider\n        self.conversation = Conversation(model=None, system=system)\n\n    def ask(self, text):\n        self.conversation.add(\"user\", text)\n        reply = self.provider.complete(self.conversation.messages)\n        self.conversation.add(\"assistant\", reply)\n        return reply"},{"t":"p","runs":[{"text":"The conversation holds message history. Its model argument is "},{"text":"None","code":true},{"text":" here because the provider owns the model choice."}]},{"t":"p","runs":[{"text":"Assistant","code":true},{"text":" "},{"text":"has a","i":true},{"text":" provider and "},{"text":"has a","i":true},{"text":" conversation. It is not a kind of either. You can hand it a fake provider in a test that returns canned text, a logging wrapper in development, or a real one in production, and "},{"text":"Assistant","code":true},{"text":" is unchanged. This is the same move as module 4’s “hand the call in”, now with an object instead of a function."}]},{"t":"p","runs":[{"text":"Composition also lets you change the provider at runtime (fall back to a cheaper model when the budget is nearly spent) which a subclass fixed at definition time cannot do."}]},{"t":"h2","id":"duck-typing-and-when-the-base-class-is-optional","runs":[{"text":"Duck typing, and when the base class is optional"}]},{"t":"p","runs":[{"text":"Python does not require the base class. Any object with a "},{"text":"complete","code":true},{"text":" method that takes those arguments will work in "},{"text":"Assistant","code":true},{"text":", whether or not it inherits from "},{"text":"ChatProvider","code":true},{"text":". That is duck typing, and it is why a test can pass in a two-line class. The base class earns its place by documenting the interface in one spot, by giving "},{"text":"isinstance","code":true},{"text":" something to check, and by making a forgotten method raise "},{"text":"NotImplementedError","code":true},{"text":" at the right line. "},{"text":"typing.Protocol","code":true},{"text":", covered later in this module, gives the same documentation without requiring inheritance at all."}]},{"t":"h2","id":"try-this-now","runs":[{"text":"Try this now"}],"role":"try"},{"t":"p","runs":[{"text":"Write "},{"text":"ChatProvider","code":true},{"text":", one real subclass against Ollama, and a "},{"text":"FakeProvider","code":true},{"text":" whose "},{"text":"complete","code":true},{"text":" returns "},{"text":"\"ok: \" + messages[-1][\"content\"]","code":true},{"text":". Build "},{"text":"Assistant","code":true},{"text":" around each and confirm the "},{"text":"Assistant","code":true},{"text":" code does not change. Then try "},{"text":"LoggingProvider","code":true},{"text":" with "},{"text":"super()","code":true},{"text":"."}]}],"check":{"question":[{"text":"A developer writes "},{"text":"class OllamaChat(OpenAIChat)","code":true},{"text":" because the two providers share a request format, overriding only "},{"text":"base_url","code":true},{"text":". Later the OpenAI class gains a method that reads "},{"text":"usage.prompt_tokens_details","code":true},{"text":" for cached-token pricing, which Ollama’s responses do not include, and every Ollama call now raises "},{"text":"AttributeError","code":true},{"text":". What went wrong structurally?"}],"options":[{"text":[{"text":"The subclass should have declared "},{"text":"__slots__","code":true},{"text":" so that attributes missing from the response would default to zero."}],"correct":false,"tempting":[{"text":"__slots__","code":true},{"text":" restricts which attributes an instance can have; it does nothing about missing keys in a response object."}]},{"text":[{"text":"Python resolves methods on the parent before the child, so the override of "},{"text":"base_url","code":true},{"text":" was ignored once a new method was added to the parent and the lookup order was recomputed."}],"correct":false,"tempting":[{"text":"Method resolution checks the child first; the override worked, and the failure is in a method the child never overrode."}]},{"text":[{"text":"The subclass inherited every future assumption of its parent, not just the request shape; two siblings under a one-method base would have stayed separate."}],"correct":true,"tempting":null},{"text":[{"text":"Subclasses cannot override attributes, only methods, so "},{"text":"base_url","code":true},{"text":" should have been passed to "},{"text":"__init__","code":true},{"text":" instead."}],"correct":false,"tempting":[{"text":"Class attributes are overridable in a subclass; the problem is not the override mechanism but what else came along with it."}]}],"order":[3,0,1,2],"why":null},"prev":{"slug":"dataclasses","title":"Dataclasses: the class that is mostly data, written in four lines","minutes":8},"next":{"slug":"dunder-methods","title":"Dunder methods: making your own objects work with len, for, in and ==","minutes":9}}}