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โ€”only List is 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 just list at 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 for list.


๐Ÿ”น 4. Type Erasure in Function Parameters

Copy

๐Ÿ” Key Takeaway:

  • Even though List[int] is specified, Python allows List[str] at runtime.


๐Ÿ”น 5. Type Erasure with Custom Generics

Copy

๐Ÿ” Key Takeaway:

  • Generic parameters (T) are erased, so Box[int] is just Box at 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__

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 with isinstance(), as it's erased at runtime.


๐Ÿ”น 9. Recovering Type Information Using get_type_hints()

Copy

๐Ÿ” Key Takeaway:

  • get_type_hints() lets us recover erased type information.


๐Ÿ”น 10. Type Checking Using isinstance() with typing Types (Fails)

Copy

๐Ÿ” Key Takeaway:

  • List[int] cannot be used in isinstance() checksโ€”only list works.


๐Ÿš€ 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