Toolbox is a small (~0.2MB) set of tools that expands the Python Standard Library.
pip install toolbox
Documentation can be found here.
Toolbox follows the same pattern as of the Python Standard Library (PSL) which means that all tools are found inside package names that corresponds to that of the PSL (e.g. asyncio
, collections
, etc.) with only one exception (config
). Check out documentation for function definitions and more details.
Runs passed function in a new thread to ensure non-blocking IO during asynchronous programming.
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())
Decorator that converts synchronous function into an asynchronous function. 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())
Performs TLS handshake on passed reader/writer stream.
from toolbox.asyncio.streams 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())
Useful pattern to add non-blocking start/stop functions and an async context manager to a class.
from toolbox import ClassTask
import asyncio
class AsyncClass(ClassTask):
def __init__(self, start: bool = False):
super().__init__(func=self.run, start=start)
async def run(self):
# Some async functionality here.
async def main():
# Use with __init__ start.
process = AsyncClass(start=True)
await asyncio.sleep(1)
process.stop()
# Use with functions to start/stop.
process = AsyncClass()
process.start()
await asyncio.sleep(1)
process.stop()
# Use with context manager to start/stop.
async with AsyncClass() as process:
...
asyncio.run(main())
Combines a property
and a classmethod
into one, creating a class property. Allows access to computed class attributes.
from toolbox import classproperty
class Animal:
@classproperty
def dog(cls):
return "whoof!"
print(Animal.dog) # >>> 'whoof!'
An interface for type-agnostic operations between different types.
from toolbox import Item
item = Item(100)
print(item == b"100" == "100" == 100) # >>> True
Dictionary with two-way capabilities.
from toolbox import BidirectionalDict
d = BidirectionalDict({"hello": "world"})
print(d) # >>> {'hello': 'world', 'world': 'hello'}
Dictionary that can be accessed as though it was an object.
from toolbox import ObjectDict
d = ObjectDict({"hello": "world"})
print(d.hello) # >>> 'world'
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'}
Dictionary that does not distinct between spaces and underscores.
from toolbox import UnderscoreAccessDict
d = UnderscoreAccessDict({"hello world": "ola mundo"})
d['hello_world'] # >>> 'ola mundo'
Dictionary that is frozen.
from toolbox import FrozenDict
d = FrozenDict({"hello": "world"})
d['ola'] = 'mundo'
# >>> KeyError: 'Cannot set key and value because this is a frozen dictionary.'
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. Example:
from toolbox import ObjectDict, UnderscoreAccessDict
class Dict(ObjectDict, UnderscoreAccessDict):
""" New dictionary that allows object access with underscore access. """
d = Dict({"hello world": "ola mundo", "100": "one hundred"})
print(d.hello_world) # >>> ola mundo
print(d._100) # >>> one hundred
Creates a nested namedtuple
for easy object access.
from toolbox import nestednamedtuple
nt = nestednamedtuple({"hello": {"ola": "mundo"}})
print(nt) # >>> namedtupled(hello=namedtupled(ola='mundo'))
print(nt.hello.ola) # >>> mundo
Forces nestednamedtuple
to not convert dict
to namedtuple
.
from toolbox import nestednamedtuple
d = {"hello": "world"}
nt = nestednamedtuple({"forced": fdict(d), "notforced": d})
print(nt.notforced) # >>> namedtupled(hello='world')
print(nt.forced) # >>> {'hello': 'world'}
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")
Access global configuration as a nestednamedtuple
.
from toolbox import conf
print(conf().hello) # >>> 'world'
Access global configuration as a dictionary.
from toolbox import config
print(config()['hello']) # >>> 'world'
Decorator that adds support for synchronous and asynchronous function timeout. Quits function after an amount of time passes.
from toolbox import timeout
@timeout(seconds=5)
def func():
time.wait(15)
func()
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'>}
All tools marked as experimental are not meant to be used in production.
Decorator for adding dispatch functionality between async and sync functions. Allows calling the same function name, one as a normal function and one as an awaitable, yet receive different results.
from toolbox import asyncdispatch
import asyncio
@asyncdispatch
def func():
return "sync"
@func.register
async def _():
return "async"
async def main():
print(func()) # >>> sync
print(await func()) # >>> async
asyncio.run(main())
Comes out of the box with built-in ANSI formats that allows text style modification.
from toolbox import bold, red
print(red("This text is red!"))
print(bold("This text is bolded!"))
Check documentation here for further information on all built-in formats.
Persistent ANSI format container that allows custom ANSI code.
from toolbox import Format
bold = Format(code=1)
print(bold("hello world"))
Persistent ANSI format container that allows multiple ANSI codes.
from toolbox import Style, red, bold
error = Style(red, bold)
print(error("This is red & bolded error."))
Returns bool that indicates whether or not the user's terminal supports color.
from toolbox import supports_color
print(supports_color())
Removes ANSI codes from string.
from toolbox import strip_ansi
print(strip_ansi("\x1b[1mhello world\x1b[0m")) # >>> hello world
Unident triple quotes and removes any white spaces before or after text.
from toolbox import unident
def test():
return unindent(
'''
hello world
this is a test
of this functionality
'''
)
print(test())
# >>> hello world
# >>> this is a test
# >>> of this functionality