Learn Python
>>> oop_advanced.interfaces

Interfaces & Duck Typing in Python

#concept

Many languages use a formal interface keyword to declare a required set of methods a class must implement. Python has no such keyword, relying instead on duck typing by default: if an object has the methods being called on it, it works, regardless of its actual class or ancestry. For cases where a more explicit, checkable contract is genuinely useful, Python's abc module (already seen in Abstraction) and the newer Protocol class from typing both provide something closer to a formal interface.

#how it works
1

No type checking happens by default

If a method exists and works on an object, calling it succeeds — nothing else is verified first.

2

This is duck typing

Any object that "quacks like a duck" (has the right methods) can be used as if it were one, with no formal declaration required.

3

Abstract base classes enforce a contract

At the cost of requiring explicit inheritance, as covered under Abstraction.

4

typing.Protocol offers a middle ground

A class can be checked against a Protocol’s shape without inheriting from it, purely by having matching methods.

5

Most everyday code relies on duck typing directly

ABCs or Protocols come in mainly for larger codebases that benefit from an explicit, checkable contract.

#example
class Duck:
def quack(self):
print("Quack!")
 
class Person:
def quack(self):
print("I'm imitating a duck!")
 
def make_it_quack(thing):
thing.quack()
 
make_it_quack(Duck())
make_it_quack(Person())
Output
Quack!
I'm imitating a duck!
1Duck and Person share no common parent class and no formal interface connects them.
2make_it_quack(thing) doesn’t check thing’s type at all — it simply calls .quack() and trusts that it exists.
3Both a real Duck and an unrelated Person work perfectly fine, since both happen to define a compatible quack() method — this is duck typing in action.
#use cases
Writing flexible functions that accept any object with the right methods, without formal type declarations
Testing code more easily, by passing in a simple fake object that just implements the methods being called
Reaching for an abstract base class instead, when a required contract genuinely needs to be enforced and checked
Using typing.Protocol for static type checking of duck-typed code, without forcing actual inheritance

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.