Python Utils
Python Utils is a module with convenient utilities not included with the standard Python install. It offers a collection of functions and classes for common patterns, including decorators, converters, formatters, and data structures like `UniqueList` and `SlicableDeque`. The library is actively maintained with frequent releases, currently at version 3.9.1.
Warnings
- gotcha When migrating from `python-utils` v2.x.x (Python 2 compatible) to v3.x.x (Python 3+), note that v3.x.x explicitly requires Python 3.9 or higher and has no other external dependencies. Compatibility with Python 2 requires the `six` package and older library versions.
- gotcha Avoid incorrect top-level imports like `import utils`. The correct package name is `python_utils`, and you should import specific classes, functions, or submodules from `python_utils` (e.g., `from python_utils import UniqueList` or `from python_utils.converters import to_int`).
- gotcha In `v3.8.2`, a fix was introduced for `fromtimestamp` overflow issues on Windows, where it previously raised a `ValueError` but can now also raise an `OSError`. This might affect code handling timestamp conversions.
Install
-
pip install python-utils
Imports
- UniqueList
from python_utils import UniqueList
- SlicableDeque
from python_utils import SlicableDeque
- to_int
from python_utils.converters import to_int
- listify
from python_utils.decorators import listify
- Logged
from python_utils.logger import Logged
Quickstart
from python_utils.converters import to_int
from python_utils.decorators import listify
# Convert a string to an integer, with a default if conversion fails
num = to_int('spam15eggs')
print(f"Converted 'spam15eggs' to {num}")
default_num = to_int('spam', default=1)
print(f"Converted 'spam' with default to {default_num}")
# Use a decorator to automatically convert a generator to a list
@listify()
def generate_numbers():
yield 1
yield 2
yield 3
my_list = generate_numbers()
print(f"Generator output as a list: {my_list}")