Python Extension Methods: Extending External APIs
Extension Methods (`extension Name on TargetType`) allow you to add new functionality to existing types (like `String`, `int`, `List`, or third-party SDK classes) without modifying the original source code or creating subclass wrappers. Extension methods are resolved statically at compile-time with zero runtime overhead.
"Extension methods are like snapping a clip-on telephoto lens onto a camera: you don't modify the internal camera electronics, but you instantly gain a new zoom capability."
Deep Dive: How It Works
Static Dispatch: Extension methods are resolved statically based on the variable's static type, resulting in zero performance penalty.
Extending Built-Ins: Add domain helpers like `str.toCapitalized()` or `5.seconds` directly onto native types.
Generic Extensions: `extension ListUtils<T> on List<T>` adds generic operations across any list type.
Syntax Blueprint
extension StringFormatting on String {
String get capitalize => isNotEmpty ? "${this[0].toUpperCase()}${substring(1)}" : "";
}
// Usage:
print("dart".capitalize); // "Dart"Extension definition adding a custom getter to String.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Trying to call an extension method on a variable typed as `dynamic`.Why it happens: Extension methods are resolved statically; dynamic variables bypass static dispatch.
How to fix: Cast the variable or assign it to a statically typed reference.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Add Squared Getter to Int
Create extension `extension MathExt on int { int get squared => this * this; }`.
In `main()`, print `9 squared: ${9.squared}`.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.