Code Explanation:
๐น 1. Importing NewType
from typing import NewType
✅ Explanation
NewType is imported from Python's built-in typing module.
It is used to create a new logical type based on an existing type.
It improves type checking and makes code easier to understand.
Think of it as giving an existing type a new identity.
typing Module
│
▼
NewType
│
Create Custom Type
Nothing is created yet.
๐น 2. Creating a New Type
UserId = NewType("UserId", int)
✅ Explanation
A new custom type named UserId is created.
Here,
"UserId" → Name of the new type
int → Base type
This means UserId behaves like an integer but has a different meaning for type checkers.
Current Memory
UserId
↓
Custom Type
↓
Based On int
Think of it as:
int
↓
UserId
It is still an integer internally.
๐น 3. Understanding NewType
NewType("UserId", int)
✅ Explanation
NewType does not create a new class.
Instead, it creates a lightweight function that simply returns the value you pass to it.
Internally, it behaves almost like this:
def UserId(value):
return value
So there is no extra object created.
Memory Representation
15
↓
UserId()
↓
15
๐น 4. Creating a UserId Object
u = UserId(15)
✅ Explanation
Python passes the value 15 to the UserId type.
Current Memory
u
↓
15
Although we call it UserId, Python actually stores it as a normal integer.
Visual Representation
UserId(15)
↓
15
↓
int
๐น 5. Understanding the Stored Value
Current Situation
u
↓
15
✅ Explanation
u is not a separate object of type UserId.
It is simply an integer value.
That's why Python treats it like this:
u = 15
The custom type name mainly helps static type checkers such as mypy.
๐น 6. Checking the Type
type(u)
✅ Explanation
Python checks the actual runtime type of u.
Current Memory
u
↓
15
Runtime Type
int
Returned object
<class 'int'>
๐น 7. Accessing the Type Name
type(u).__name__
✅ Explanation
type(u) returns
<class 'int'>
The __name__ attribute extracts only the class name.
Result
int
๐น 8. Printing the Result
print(type(u).__name__)
✅ Explanation
Python prints the type name.
Output
int
๐ฏ Final Output
int

0 Comments:
Post a Comment