Python Const Constructors & Canonical Instance Caching
If a class produces objects that never change, you can declare a **`const` constructor**. All instance variables in a const class must be `final`. When multiple `const` instances are created with identical arguments, the compiler reuses a single canonical memory instance, drastically reducing garbage collector pressure and speeding up Flutter UI rebuilding.
"`const` constructors are like currency coins minted at the treasury: every 2026 quarter is identical in every dimension, so rather than manufacturing a new coin design for every purchase, the economy reuses the standard canonical quarter."
Deep Dive: How It Works
Canonicalization: `identical(const Point(1, 1), const Point(1, 1))` evaluates to `true` (same memory address).
Immutable Requirement: Every field in a class with a const constructor MUST be marked `final`.
Flutter Performance: Widgets marked `const` are skipped by Flutter's layout and rendering tree during widget rebuilds.
Syntax Blueprint
class ImmutableColor {
final int r, g, b;
const ImmutableColor(this.r, this.g, this.b);
}
// Canonical instance
const red1 = ImmutableColor(255, 0, 0);
const red2 = ImmutableColor(255, 0, 0);
print(identical(red1, red2)); // true!Const constructor producing canonicalized identical memory instances.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Trying to add a `const` constructor to a class with non-final fields.Why it happens: Mutable fields cannot be compile-time constants.
How to fix: Ensure all fields are declared `final`.
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.
Create Const Coordinate Class
Create class `Coord` with `final int x, y; const Coord(this.x, this.y);`.
In `main()`, declare `const c1 = Coord(5, 10); const c2 = Coord(5, 10);`.
Print `Identical: ${identical(c1, c2)}`.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.