🧰 Toolbox
Toolbox is a small (~0.2MB) set of tools that expands the Python Standard Library.
Installing
pip install toolbox
Documentation
Documentation can be found here.
Tools
asyncio
future_lru_cache — lru_cache for async functions.
from toolbox import future_lru_cache
import asyncio
@future_lru_cache
async def func():
await asyncio.sleep(10)
return 42
async def main():
await func() # Runs once.
await func() # Returns cached value.
asyncio.run(main())
to_thread — Run a synchronous function in a separate thread.
from toolbox import to_thread
import asyncio
import time
def func():
time.sleep(2)
return "Hello world"
async def main():
await to_thread(func)
asyncio.run(main())
awaitable — Convert synchronous function to an async function via thread.
Leverages the to_thread function above.
from toolbox import awaitable
import asyncio
import time
@awaitable
def func():
time.sleep(2)
return "Hello world"
async def main():
await func()
asyncio.run(func())
tls_handshake — Perform TLS handshake with a stream reader & writer.
from toolbox import tls_handshake
import asyncio
async def client():
reader, writer = await asyncio.open_connection("httpbin.org", 443, ssl=False)
await tls_handshake(reader=reader, writer=writer)
# Communication is now encrypted.
asyncio.run(client())
CoroutineClass — Class pattern for implementing object-based coroutines.
Pattern for creating a coroutine-like class that has multiple ways to start it.
from toolbox import CoroutineClass
import asyncio
class Coroutine(CoroutineClass):
def __init__(self, run: bool = False):
super().__init__(run=run)
# Default entry function.
async def entry(self):
await asyncio.sleep(1)
return "Hello world"
# Start coroutine outside Python async context.
def iomain():
# via __init__
coro = Coroutine(run=True)
print(coro.result) # Hello world
# via .run()
coro = Coroutine()
result = coro.run()
print(result) # Hello world
# Start coroutine inside Python async context.
async def aiomain():
# via __init__
coro = Coroutine(run=True)
await asyncio.sleep(1)
coro.stop()
print(coro.result) # None - because process was stopped before completion.
# via .run()
coro = Coroutine()
coro.run()
await asyncio.sleep(1)
result = coro.stop() # None - because coroutine was stopped before completion.
print(result) # Hello world
# via await
coro = Coroutine()
result = await coro # You can also start, and await later.
print(result) # Hello World
# via context manager
async with Coroutine() as coro:
result = await coro
print(result) # Hello World
builtins
classproperty — Decorator for defining a method as a property and classmethod.
Allows access to computed class attributes.
from toolbox import classproperty
class Animal:
@classproperty
def dog(cls):
return "whoof!"
print(Animal.dog) # 'whoof!'
collections
Item — An interface for type-agnostic operations between different types.
from toolbox import Item
item = Item(100)
print(item == b"100" == "100" == 100) # True
nestednamedtuple — Creates a nested namedtuple.
from toolbox import nestednamedtuple
nt = nestednamedtuple({"hello": {"ola": "mundo"}})
print(nt) # namedtupled(hello=namedtupled(ola='mundo'))
print(nt.hello.ola) # mundo
fdict — Forces nestednamedtuple to not convert dict to namedtuple.
from toolbox import nestednamedtuple, fdict
d = {"hello": "world"}
nt = nestednamedtuple({"forced": fdict(d), "notforced": d})
print(nt.notforced) # namedtupled(hello='world')
print(nt.forced) # {'hello': 'world'}
BidirectionalDict — Dictionary with two-way capabilities.
from toolbox import BidirectionalDict
d = BidirectionalDict({"hello": "world"})
print(d) # {'hello': 'world', 'world': 'hello'}
ObjectDict — Dictionary that can be accessed as though it was an object.
from toolbox import ObjectDict
d = ObjectDict({"hello": "world"})
print(d.hello) # 'world'
OverloadedDict — Dictionary that can be added or subtracted to.
from toolbox import OverloadedDict
d1 = OverloadedDict({"hello": "world"})
d2 = OverloadedDict({"ola": "mundo"})
d1 += d2
print(d1) # {'hello': 'world', 'ola': 'mundo'}
d1 -= d2
print(d1) # {'hello': 'world'}
UnderscoreAccessDict — Dictionary with underscore access.
from toolbox import UnderscoreAccessDict
d = UnderscoreAccessDict({"hello": "world"})
print(d.hello) # 'world'
FrozenDict — Dictionary that is frozen.
from toolbox import FrozenDict
d = FrozenDict({"hello": "world"})
d["hello"] = "mundo" # KeyError: Cannot set key and value because this is a frozen dictionary.
MultiEntryDict — Dictionary that can have multiple entries for the same key.
from toolbox import MultiEntryDict
d = MultiEntryDict({"hello": "world"})
d["hello"] = "mundo"
print(d) # {'hello': ['world', 'mundo']}
ItemDict — Dictionary that utilizes Item for key and values.
from toolbox import ItemDict, Item
d = ItemDict({"100": "one hundred"})
print(d[100]) # one hundred
print(d[100] == d['100'] == d[b'100'] == d[Item(100)]) # True
All *Dict types above can be combined together (as mixins) to create unique dictionary types.
config
make_config — Stores configuration dictionary in-memory.
Creates a global configuration that can be accessed by other portions of the code via conf or config function calls. Minimizes the need to create Config objects and pass them around different modules, classes, functions, etc.
from toolbox import make_config
make_config(hello="world")
config — Access in-memory configuration as dictionary.
from toolbox import config
print(config()['hello']) # 'world'
conf — Access in-memory configuration as nestednametuple.
from toolbox import conf
print(conf().hello) # 'world'
functools
timeout — Decorator to add timeout for synchronous and asychronous functions.
Decorator that adds support for synchronous and asynchronous function timeout. Quits function after an amount of time passes.
from toolbox import timeout
import asyncio
import time
@timeout(seconds=1)
def func():
time.sleep(15)
@timeout(seconds=1)
async def func():
await asyncio.sleep(15)
pdb
sprinkle — Prints the line and file that this function was just called from.
from toolbox.pdb.sprinkle import sprinkle
sprinkle() # >>> 3 this_file.py
sprinkle("hello", "world") # >>> 4 this_file.py hello world
pkgutil
search_package — Searches for packages installed in the system.
from toolbox import search_package
print(search_package("toolbox", method="is"))
# {'toolbox': <module 'toolbox' from '.../toolbox/__init__.py'>}
sockets
is_ip — Checks if a string is an IP address.
from toolbox import is_ip
print(is_ip('127.0.0.1')) # True
print(is_ip('localhost')) # False
string
ANSI Formatting — Color formatting.
Check documentation here for further information on all built-in formats.
from toolbox import bold, red
print(red("This text is red!"))
print(bold("This text is bolded!"))
Format — Persistent ANSI formatter that takes a custom ANSI code.
from toolbox import Format
bold = Format(code=1)
print(bold("hello world"))
Style — Persistent ANSI formatter that allows multiple ANSI codes.
from toolbox import Style, red, bold
error = Style(red, bold)
print(error("This is red & bolded error."))
supports_color — Check's if the user's terminal supports color.
from toolbox import supports_color
print(supports_color()) # True
strip_ansi — Removes ANSI codes from string.
from toolbox import strip_ansi
print(strip_ansi("\x1b[1mhello world\x1b[0m")) # hello world
textwrap
unindent — Removes indent and white-space from docstrings.
from toolbox import unindent
def test():
text = """
hello world
this is a test
"""
print(text)
text = unindent(
"""
hello world
this is a test
"""
)
print(text)
test()
# hello world
# this is a test
#
# hello world
# this is a test
Metadata
Release files for toolbox 1.11.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| toolbox-1.11.0.tar.gz | 33.2 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| toolbox-1.11.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 58.0 kB
Release files / toolbox-1.11.0.tar.gz
| Download URL | toolbox-1.11.0.tar.gz |
|---|---|
| Size | 33.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
9a7c2a2e1ddbbcdf212c0a8cc895473b674814aec978d6538f1ffd595ae6469b
|
|
BLAKE2b-256 checksum How to use checksums |
544227357827649818b5b6cc86c1b90138e4016b1dd6e469c6b05ae0374ed95e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/4.0.2 CPython/3.11.3
|
Release files / toolbox-1.11.0-py3-none-any.whl
| Download URL | toolbox-1.11.0-py3-none-any.whl |
|---|---|
| Size | 24.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
66ab4a8a5e08580c26f1019bb30b04e2af847e86346e9bddd6b6b50b2de7b7ff
|
|
BLAKE2b-256 checksum How to use checksums |
3fdd12351603b9902e36f16ce11a300bed44b2615f7bb096e1aeb1e5572de733
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/4.0.2 CPython/3.11.3
|