Skip to content


Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Latest commit

Added extra containers such as UniqueList and SlicableDeque. Added full pyright strict and mypy type checks v3.6.0

# aV0dzhAAk43taonhO4EVtC0Dr3LC6Ed/mr6MbQiFmWU1AoXUYslXZiKPCySFwxUb
# oAs0rfJjMeYOj9+W+clj5rbPfwZAyVdmN8t7eStDus3xPnWtzK7VmgvwEYXgdc9g
# TeZomgW7awldL2hIiaL0YM7BdtkbmN45F8wLXMp84CTFVFAMRtIR4ME7QgHsIbGt
# DMGXzPzk6uO0dq/N11x5FDZO9E/Tbhrj6p1e43OpFOUHJl5ywCa7N23K6Q0kgTYh
# 76YUoEclfZDUrULE409YbXUGZYto1LCdbT+IikluiDBX/2CajuZGpUlCksyHqaCy
# tZvp+0vnT4qKn8FYJQpTVD1M0iNXS6t18h655Z0bsN1fsgQb8ghW6coQNlhxaR68
# 8wz8MyxAjMAU5je5j+Ysfd05SRn+nGT15wkxWhwCtJvuLHdF5Vu2QxOBvKoPk2xE
# vVYpHDYJ4krEMPgHz4/Lq/K2j48q62uIDRNopppgyU8oZGkYtQghZasEVZKbfTDJ
# nlRlLMDtUqznKFwEF6yWKanAaT8qoPMJH2qqKopUPEnf4JuFtAitqtXniwSMRg7x
# +YFxOz7iZxNTaFDVwv2FiOPPBfM+/Icgs1I0tW62X6v26geLpIDk9AJRRsOUlH+g
# pTbgM1XE1ux68cZi9Qd8z7BZMDRgcybycFhvCc2rborbwCnn1xs=
# =nS2b
# gpg: Signature made Mon May 29 02:58:50 2023 CEST
# gpg:                using RSA key 149325FD15904E9C4EB89E95E81444E9CE1F695D
# gpg: Good signature from "Rick van Hattem <>" [ultimate]
# gpg:                 aka "[jpeg image of size 9662]" [ultimate]

Git stats


Failed to load latest commit information.

Useful Python Utils

Python Utils is a collection of small Python functions and classes which make common patterns shorter and easier. It is by no means a complete collection but it has served me quite a bit in the past and I will keep extending it.

One of the libraries using Python Utils is Django Utils.

Documentation is available at:


Security contact information

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.

Requirements for installing:

For the Python 3+ release (i.e. v3.0.0 or higher) there are no requirements. For the Python 2 compatible version (v2.x.x) the six package is needed.


The package can be installed through pip (this is the recommended method):

pip install python-utils

Or if pip is not available, easy_install should work as well:

easy_install python-utils

Or download the latest release from Pypi ( or Github.

Note that the releases on Pypi are signed with my GPG key ( and can be checked using GPG:

gpg --verify python-utils-<version>.tar.gz.asc python-utils-<version>.tar.gz


This module makes it easy to execute common tasks in Python scripts such as converting text to numbers and making sure a string is in unicode or bytes format.


Automatically converting a generator to a list, dict or other collections using a decorator:

>>> @decorators.listify()
... def generate_list():
...     yield 1
...     yield 2
...     yield 3
>>> generate_list()
[1, 2, 3]

>>> @listify(collection=dict)
... def dict_generator():
...     yield 'a', 1
...     yield 'b', 2

>>> dict_generator()
{'a': 1, 'b': 2}

Retrying until timeout

To easily retry a block of code with a configurable timeout, you can use the time.timeout_generator:

>>> for i in time.timeout_generator(10):
...     try:
...         # Run your code here
...     except Exception as e:
...         # Handle the exception

Formatting of timestamps, dates and times

Easy formatting of timestamps and calculating the time since:

>>> time.format_time('1')
>>> time.format_time(1.234)
>>> time.format_time(1)
>>> time.format_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6))
'2000-01-02 03:04:05'
>>> time.format_time(, 1, 2))
>>> time.format_time(datetime.timedelta(seconds=3661))
>>> time.format_time(None)

>>> formatters.timesince(now)
'just now'
>>> formatters.timesince(now - datetime.timedelta(seconds=1))
'1 second ago'
>>> formatters.timesince(now - datetime.timedelta(seconds=2))
'2 seconds ago'
>>> formatters.timesince(now - datetime.timedelta(seconds=60))
'1 minute ago'

Converting your test from camel-case to underscores:

>>> camel_to_underscore('SpamEggsAndBacon')

Attribute setting decorator. Very useful for the Django admin

A convenient decorator to set function attributes using a decorator:

You can use:
>>> @decorators.set_attributes(short_description='Name')
... def upper_case_name(self, obj):
...     return ("%s %s" % (obj.first_name, obj.last_name)).upper()

Instead of:
>>> def upper_case_name(obj):
...     return ("%s %s" % (obj.first_name, obj.last_name)).upper()

>>> upper_case_name.short_description = 'Name'

This can be very useful for the Django admin as it allows you to have all metadata in one place.

Scaling numbers between ranges

>>> converters.remap(500, old_min=0, old_max=1000, new_min=0, new_max=100)

# Or with decimals:
>>> remap(decimal.Decimal('250.0'), 0.0, 1000.0, 0.0, 100.0)

Get the screen/window/terminal size in characters:

>>> terminal.get_terminal_size()
(80, 24)

That method supports IPython and Jupyter as well as regular shells, using blessings and other modules depending on what is available.

Extracting numbers from nearly every string:

>>> converters.to_int('spam15eggs')
>>> converters.to_int('spam')
>>> number = converters.to_int('spam', default=1)

Doing a global import of all the modules in a package programmatically:

To do a global import programmatically you can use the import_global function. This effectively emulates a from ... import *

from python_utils.import_ import import_global

# The following is  the equivalent of `from some_module import *`

Automatically named logger for classes:

Or add a correclty named logger to your classes which can be easily accessed:

class MyClass(Logged):
    def __init__(self):

my_class = MyClass()

# Accessing the logging method:

# With formatting:
my_class.error('The logger supports %(formatting)s',
               formatting='named parameters')

# Or to access the actual log function (overwriting the log formatting can
# be done n the log method)
import logging
my_class.log(logging.ERROR, 'log')

Alternatively loguru is also supported. It is largely a drop-in replacement for the logging module which is a bit more convenient to configure:

First install the extra loguru package:

pip install 'python-utils[loguru]'
class MyClass(Logurud):

Now you can use the Logurud class to make functions such as available. The benefit of this approach is that you can add extra context or options to you specific loguru instance (i.e. self.logger):

Convenient type aliases and some commonly used types:

# For type hinting scopes such as locals/globals/vars
Scope = Dict[str, Any]
OptionalScope = O[Scope]

# Note that Number is only useful for extra clarity since float
# will work for both int and float in practice.
Number = U[int, float]
DecimalNumber = U[Number, decimal.Decimal]

# To accept an exception or list of exceptions
ExceptionType = Type[Exception]
ExceptionsType = U[Tuple[ExceptionType, ...], ExceptionType]

# Matching string/bytes types:
StringTypes = U[str, bytes]