214. Type Erasure in Python
๐น 1. Type Hints Are Erased at Runtime
Copy
from typing import List
def process_data(data: List[int]):
print(f"Received: {data}")
print(process_data.__annotations__)
# Output: {'data': typing.List[int]} (Only visible in annotations, not enforced)๐ Key Takeaway:
List[int]does not exist at runtimeโonlyListis used.Type hints are stored in
__annotations__, but Python does not enforce them.
๐น 2. Generic Type Arguments Are Not Retained
Copy
from typing import List
lst: List[int] = [1, 2, 3]
print(type(lst)) # <class 'list'> (No int information retained)๐ Key Takeaway:
List[int]becomes justlistat runtimeโtype information is erased.
๐น 3. Checking If a Variable is a List (Without Type Info)
Copy
๐ Key Takeaway:
List[int]is completely erased at runtime, so we only check forlist.
๐น 4. Type Erasure in Function Parameters
Copy
๐ Key Takeaway:
Even though
List[int]is specified, Python allowsList[str]at runtime.
๐น 5. Type Erasure with Custom Generics
Copy
๐ Key Takeaway:
Generic parameters (
T) are erased, soBox[int]is justBoxat runtime.
๐น 6. Type Annotations vs. Actual Behavior
Copy
๐ Key Takeaway:
Python does not enforce type hints at runtime; they are just for static checks.
๐น 7. Checking a Type Using __orig_bases__
__orig_bases__Copy
๐ Key Takeaway:
While type arguments are erased, they can be accessed using
__orig_bases__.
๐น 8. Type Erasure in Subclassing
Copy
๐ Key Takeaway:
List[int]cannot be used withisinstance(), as it's erased at runtime.
๐น 9. Recovering Type Information Using get_type_hints()
get_type_hints()Copy
๐ Key Takeaway:
get_type_hints()lets us recover erased type information.
๐น 10. Type Checking Using isinstance() with typing Types (Fails)
isinstance() with typing Types (Fails)Copy
๐ Key Takeaway:
List[int]cannot be used inisinstance()checksโonlylistworks.
๐ Summary: Type Erasure in Python
Concept
Description
Type Hints Are Ignored at Runtime
Python does not enforce type hints during execution.
Generic Types Become Their Base Type
List[int] becomes just list.
No Type Checking for Function Arguments
Python allows mismatched types at runtime.
Type Information Can Be Retrieved
Use __annotations__ or get_type_hints().
Cannot Use isinstance() with List[int]
It raises an errorโuse list instead.
๐ Best Practices
โ
Use Type Hints for Readability, Not Enforcement โ
Use Static Type Checkers (e.g., mypy) for Catching Errors โ
Remember That Generics Are Erased at Runtime โ
Use get_type_hints() for Type Introspection
Last updated