Package: toolbox
🧰 ToolboxToolbox is a small (~0.2MB) set of tools that expands thePython Standard Library.Installingpip install toolboxDocumentationDocumentation can be foundhere.Toolsasynciofuture_lru_cache—lru_cachefor async functions.fromtoolboximportfuture_lru_cacheimportasyncio@future_lru_cacheasyncdeffunc():awaitasyncio.sleep(10)return42asyncdefmain():awaitfunc()# Runs once.awaitfunc()# Returns cached value.asyncio.run(main())to_thread— Run a synchronous function in a separate thread.fromtoolboximportto_threadimportasyncioimporttimedeffunc():time.sleep(2)return"Hello world"asyncdefmain():awaitto_thread(func)asyncio.run(main())awaitable— Convert synchronous function to an async function via thread.Leverages theto_threadfunction above.fromtoolboximportawaitableimportasyncioimporttime@awaitabledeffunc():time.sleep(2)return"Hello world"asyncdefmain():awaitfunc()asyncio.run(func())tls_handshake— Perform TLS handshake with a stream reader & writer.fromtoolboximporttls_handshakeimportasyncioasyncdefclient():reader,writer=awaitasyncio.open_connection("httpbin.org",443,ssl=False)awaittls_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.fromtoolboximportCoroutineClassimportasyncioclassCoroutine(CoroutineClass):def__init__(self,run:bool=False):super().__init__(run=run)# Default entry function.asyncdefentry(self):awaitasyncio.sleep(1)return"Hello world"# Start coroutine outside Python async context.defiomain():# 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.asyncdefaiomain():# via __init__coro=Coroutine(run=True)awaitasyncio.sleep(1)coro.stop()print(coro.result)# None - because process was stopped before completion.# via .run()coro=Coroutine()coro.run()awaitasyncio.sleep(1)result=coro.stop()# None - because coroutine was stopped before completion.print(result)# Hello world# via awaitcoro=Coroutine()result=awaitcoro# You can also start, and await later.print(result)# Hello World# via context managerasyncwithCoroutine()ascoro:result=awaitcoroprint(result)# Hello Worldbuiltinsclassproperty— Decorator for defining a method as a property and classmethod.Allows access to computed class attributes.fromtoolboximportclasspropertyclassAnimal:@classpropertydefdog(cls):return"whoof!"print(Animal.dog)#  'whoof!'collectionsItem— An interface for type-agnostic operations between different types.fromtoolboximportItemitem=Item(100)print(item==b"100"=="100"==100)#  Truenestednamedtuple— Creates a nestednamedtuple.fromtoolboximportnestednamedtuplent=nestednamedtuple({"hello":{"ola":"mundo"}})print(nt)#  namedtupled(hello=namedtupled(ola='mundo'))print(nt.hello.ola)#  mundofdict— Forcesnestednamedtupleto not convertdicttonamedtuple.fromtoolboximportnestednamedtuple,fdictd={"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.fromtoolboximportBidirectionalDictd=BidirectionalDict({"hello":"world"})print(d)#  {'hello': 'world', 'world': 'hello'}ObjectDict— Dictionary that can be accessed as though it was an object.fromtoolboximportObjectDictd=ObjectDict({"hello":"world"})print(d.hello)#  'world'OverloadedDict— Dictionary that can be added or subtracted to.fromtoolboximportOverloadedDictd1=OverloadedDict({"hello":"world"})d2=OverloadedDict({"ola":"mundo"})d1+=d2print(d1)#  {'hello': 'world', 'ola': 'mundo'}d1-=d2print(d1)#  {'hello': 'world'}UnderscoreAccessDict— Dictionary with underscore access.fromtoolboximportUnderscoreAccessDictd=UnderscoreAccessDict({"hello":"world"})print(d.hello)#  'world'FrozenDict— Dictionary that is frozen.fromtoolboximportFrozenDictd=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.fromtoolboximportMultiEntryDictd=MultiEntryDict({"hello":"world"})d["hello"]="mundo"print(d)#  {'hello': ['world', 'mundo']}ItemDict— Dictionary that utilizesItemfor key and values.fromtoolboximportItemDict,Itemd=ItemDict({"100":"one hundred"})print(d[100])#  one hundredprint(d[100]==d['100']==d[b'100']==d[Item(100)])#  TrueAll*Dicttypes above can be combined together (as mixins) to create unique dictionary types.configmake_config— Stores configuration dictionary in-memory.Creates a global configuration that can be accessed by other portions of the code viaconforconfigfunction calls. Minimizes the need to createConfigobjects and pass them around different modules, classes, functions, etc.fromtoolboximportmake_configmake_config(hello="world")config— Access in-memory configuration as dictionary.fromtoolboximportconfigprint(config()['hello'])#  'world'conf— Access in-memory configuration asnestednametuple.fromtoolboximportconfprint(conf().hello)#  'world'functoolstimeout— 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.fromtoolboximporttimeoutimportasyncioimporttime@timeout(seconds=1)deffunc():time.sleep(15)@timeout(seconds=1)asyncdeffunc():awaitasyncio.sleep(15)pdbsprinkle—  Prints the line and file that this function was just called from.fromtoolbox.pdb.sprinkleimportsprinklesprinkle()# >>> 3 this_file.pysprinkle("hello","world")# >>> 4 this_file.py hello worldpkgutilsearch_package— Searches for packages installed in the system.fromtoolboximportsearch_packageprint(search_package("toolbox",method="is"))#  {'toolbox': <module 'toolbox' from '.../toolbox/__init__.py'>}socketsis_ip— Checks if a string is an IP address.fromtoolboximportis_ipprint(is_ip('127.0.0.1'))# Trueprint(is_ip('localhost'))# FalsestringANSI Formatting— Color formatting.Check documentationherefor further information on all built-in formats.fromtoolboximportbold,redprint(red("This text is red!"))print(bold("This text is bolded!"))Format— Persistent ANSI formatter that takes a custom ANSI code.fromtoolboximportFormatbold=Format(code=1)print(bold("hello world"))Style— Persistent ANSI formatter that allows multiple ANSI codes.fromtoolboximportStyle,red,bolderror=Style(red,bold)print(error("This is red & bolded error."))supports_color— Check's if the user's terminal supports color.fromtoolboximportsupports_colorprint(supports_color())# Truestrip_ansi— Removes ANSI codes from string.fromtoolboximportstrip_ansiprint(strip_ansi("\x1b[1mhello world\x1b[0m"))#  hello worldtextwrapunindent— Removes indent and white-space from docstrings.fromtoolboximportunindentdeftest():text="""hello worldthis is a test"""print(text)text=unindent("""hello worldthis is a test""")print(text)test()#           hello world#           this is a test## hello world# this is a test