Lesson 27 of 55
10 mins readPython Defining Custom Typeclasses & Instances
In Plain English
Create your own typeclasses using the class keyword and implement them for concrete types using instance declarations.
Deep Dive: How It Works
class Declaration: class Describable a where describe :: a -> String.
instance Implementation: instance Describable Bool where describe True = "Yes"; describe False = "No".
Default Implementations: Typeclasses can provide default method implementations that instances can optionally override.
Core Rules to Remember

class Keyword: Defines a new typeclass interface and required method signatures.

instance Keyword: Provides the concrete implementation of the typeclass for a specific type.
Live Interactive Example
Hit Run Code to see it liveCustom Describable Typeclass
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: describe dynamically resolves to the appropriate instance implementation.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Implement Sizeable Instance
Define `class Sizeable a where size :: a -> Int`.
Implement `instance Sizeable Int where size _ = 1`.
Print `"Size: "` followed by `show (size (99 :: Int))`.
1
2
3
4
5
6
7
8
9
10
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.