Code Explanation:
๐น 1. Importing singledispatch
from functools import singledispatch
✅ Explanation
singledispatch is a decorator from Python's functools module.
It allows one function to have multiple implementations based on the type of the first argument.
This feature is called Single Dispatch Generic Functions.
functools
│
▼
singledispatch
↓
One Function
↓
Different Implementations
↓
int
str
list
float
...
Nothing is executed yet.
๐น 2. Creating the Default Function
@singledispatch
def show(x):
print("Default")
✅ Explanation
This creates the default version of show().
Whenever Python cannot find a matching registered type, it executes this function.
Current Memory
show()
↓
Default Version
↓
print("Default")
Currently only one implementation exists.
๐น 3. Registering the int Version
@show.register(int)
def _(x):
print("Integer")
✅ Explanation
A new implementation is registered for the int type.
Now show() has two implementations.
Current Memory
show()
├── Default
│
└── int
Visual Representation
show()
┌──────────────┐
│ Dispatcher │
└──────────────┘
│
┌──────┴──────┐
▼ ▼
Default Integer
๐น 4. Calling the Function
show(True)
✅ Explanation
At first glance,
True
looks like a Boolean.
But here's the trick.
Python internally treats
bool
as a subclass of
int
You can verify it:
issubclass(bool, int)
Output
True
Current Memory
Argument
↓
True
↓
Type
↓
bool
↓
bool inherits int
๐น 5. Dispatching Process
When Python receives
show(True)
it checks:
Is there a bool implementation?
↓
No
↓
Is bool a subclass of another registered type?
↓
Yes
↓
int
↓
Execute int version
Therefore,
print("Integer")
is executed.
๐น 6. Printing the Result
Output
Integer
๐ฏ Final Output
Integer

0 Comments:
Post a Comment