Lesson 28 of 55
15 mins readPython Generic Constraints with extends
In Plain English
Generic constraints (<T extends Shape>) enforce structural prerequisites on type parameters, allowing safe access to required properties.
Core Rules to Remember

extends Constraint: <T extends Shape> ensures T satisfies the given structural contract.

Safe Property Access: Unlocks member property access (like .length or .id) directly on generic arguments.
Live Interactive Example
Hit Run Code to see it liveConstraining Type Parameters
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Output Console
Click "Run Code" to view the rendered output.
How it works: Because T extends HasLength, accessing a.length is completely type-safe.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Constrain to Identifiable Entity
Declare interface HasId { id: string | number }.
Write generic function printEntityId<T extends HasId>(entity: T): string returning `Entity ID: ${entity.id}`.
Call with { id: "srv-99", name: "Cluster" } and print.
1
2
3
4
5
6
7
8
9
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.