CodeBlanks Logo Icon CodeBlanks

Protocol

Learn structural typing with typing.Protocol.

What is Protocol for?

Protocol provides structural typing. Even without inheriting from a Protocol, a class is considered conforming if it has the right methods. It is imported from the typing module.

Example: class Drawable(Protocol):\n def draw(self) -> str: .... Any class that provides draw is considered a Drawable; it does not need to inherit. With @runtime_checkable you can also enable isinstance checks.

@runtime_checkable

To check a protocol with isinstance you use the @runtime_checkable decorator. It decides conformance by looking only at method signatures on the protocol.

Example: @runtime_checkable\nclass Speaker(Protocol):\n def speak(self) -> str: .... The call isinstance(obj, Speaker) returns True if obj has a speak method. This is the most practical way to check conformance without an inheritance relationship.

Practice Drawable protocol and Circle

Start with from typing import Protocol, runtime_checkable. Define @runtime_checkable and class Drawable(Protocol):; inside, write def draw(self) -> str: .... Then define class Circle: (no inheritance); in the body write def draw(self) -> str: and return "circle". Finally create c = Circle() and print conformance with print(isinstance(c, Drawable)).

Starter code

main.py
# Write the Drawable protocol and the Circle class

Sample solution

main.py
# Write the Drawable protocol and the Circle class
from typing import Protocol, runtime_checkable

@runtime_checkable
class Drawable(Protocol):
    def draw(self) -> str: ...

class Circle:
    def draw(self) -> str:
        return "circle"

c = Circle()
print(isinstance(c, Drawable))

Expected output

True

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the Protocol parts

Term Meaning
Protocol Base class
typing Module
@runtime_checkable isinstance permission
def draw(self) Expected method

2 What is needed to conform to a Protocol?

  • Having the right methods Correct answer
  • Filling abstract methods
  • Inheriting ABC
  • Inheritance

Explanation: Protocol accepts having the right methods; no inheritance required.

3 Protocol import line

Question
from typing import Protocol, ____

@runtime_checkable
class Drawable(Protocol):
    def draw(self) -> str: ...
Answer
from typing import Protocol, runtime_checkable

@runtime_checkable
class Drawable(Protocol):
    def draw(self) -> str: ...

Explanation: runtime_checkable is imported from the typing module.

All lessons in Intermediate