Python Subtypes
pysubtypes is a Python library that provides subclasses for common Python built-in types (like Str, Int, List, Dict) with additional functionality and convenience methods. It aims to enhance native types with common utility methods and properties. The library maintains a frequent release cadence, primarily with patch versions, and is currently at version 0.3.18.
Warnings
- gotcha When subclassing built-in types, be aware that not all native C-level optimizations and behaviors of the original types may be fully preserved. While `pysubtypes` aims for compatibility, some subtle differences in performance or memory usage might occur.
- gotcha The library heavily relies on implicit `__call__` and other magic methods for its convenience features. This can sometimes lead to unexpected behavior if you're not familiar with how these methods are overloaded, especially when chaining operations or passing `pysubtypes` instances to functions expecting strict built-in types.
- gotcha Direct instantiation of built-in types might be preferred in performance-critical loops due to the overhead introduced by subclassing and additional method lookups. The utility of `pysubtypes` shines in code readability and expressiveness over raw speed for basic operations.
Install
-
pip install pysubtypes
Imports
- Str
from subtypes import Str
- Int
from subtypes import Int
- List
from subtypes import List
- Dict
from subtypes import Dict
- AnyString
from subtypes import AnyString
Quickstart
from subtypes import Str, List
# Enhanced string functionality
my_string = Str("Hello world")
formatted_string = my_string("from the other side")
print(f"Formatted string: {formatted_string}")
print(f"Title case: {my_string.title}")
# Enhanced list functionality
my_list = List([1, 2, 3])
my_list.append_unique(2)
my_list.append_unique(4)
print(f"Unique appends: {my_list}")
# Accessing underlying native type
print(f"Native list: {my_list.native}")