Package: pyassorted
pyassortedA library has assorted utils in Pure-Python. There are 3 principles:Light-weightNo dependenciesPythonic usage.Documentation:https://dockhardman.github.io/pyassorted/PYPI:https://pypi.org/project/pyassorted/InstallationpipinstallpyassortedModulespyassorted.asyncio.executorpyassorted.asyncio.iopyassorted.asyncio.utilspyassorted.cache.cachepyassorted.collections.sqlitedictpyassorted.datetimepyassorted.io.watchpyassorted.lock.filelockModules Description and Usagespyassorted.asyncioThis Python module,pyassorted.asyncio, provides utility functions to facilitate easier and more effective asynchronous programming using Python's built-inasynciolibrary.It provides a level of abstraction over some of the complexities of theasyncioandconcurrent.futureslibrary.importasynciofrompyassorted.asyncioimportrun_funcdefnormal_func()->bool:returnTrueasyncdefasync_func()->bool:awaitasyncio.sleep(0.0)returnTrueasyncmain():assertawaitrun_func(normal_func)isTrueassertawaitrun_func(async_func)isTrueasyncio.run(main())pyassorted.asyncio.ioTheaio_openfunction serves as a replacement for Python's built-in open function, creating an instance of theAsyncIOWrapperwhen invoked. It is designed to work in an async with block and follows a similar interface to the standardopenfunction.importasynciofrompyassorted.ioimportaio_openasyncdefmain():# Write to a fileasyncwithaio_open("file.txt","w")asf:awaitf.write("Hello")# Read file contentasyncwithaio_open("file.txt")asf:assert(awaitf.read())=="Hello"asyncio.run(main())pyassorted.cachepyassorted.cacheis a Python module that provides an interface for caching data to enhance performance by reducing expensive or time-consuming function calls and computations.It includes the implementation of the Least Recently Used (LRU) cache policy and acacheddecorator for easy application of caching to any function or coroutine function.importasynciofrompyassorted.cacheimportLRU,cachedlru_cache=LRU()# Cache function@cached(lru_cache)defadd(a:int,b:int)->int:returna+bassertadd(1,2)==3assertlru_cache.hits==0assertlru_cache.misses==1assertadd(1,2)==3assertlru_cache.hits==1assertlru_cache.misses==1# Cache coroutine@cached(lru_cache)asyncdefasync_add(a:int,b:int)->int:awaitasyncio.sleep(0)returna+bassertadd(1,2)==3assertlru_cache.hits==2assertlru_cache.misses==1pyassorted.collections.sqlitedictThepyassorted.collections.sqlitedictmodule provides a dictionary-like interface to SQLite databases. This can be used as a persistent dictionary for Python objects, where keys are restricted to primitive types such as strings and numbers.The SqliteDict class supports common dictionary operations like getting, setting, and determining the length, with the added feature of enabling these operations asynchronously.Theasync_setandasync_getmethods use an asynchronous execution pattern, which can be very useful in applications with high IO operations, like web or network servers.importasynciofrompyassorted.collections.sqlitedictimportSqliteDictsql_dict=SqliteDict(":memory:")sql_dict["key"]="value"assertsql_dict["key"]=="value"# Asynchronous usageasyncdefmain():awaitsql_dict.async_set("key","value")assert(awaitsql_dict.async_get("key"))=="value"asyncio.run(main())pyassorted.datetimeThepyassorted.datetimemodule offers various utilities for managing and interacting with date and time in Python.This module comprises two primary functions:aware_datetime_nowandiso_datetime_now. Theaware_datetime_nowfunction provides the current datetime in a specified timezone, using pytz's timezone conversions for enhanced accuracy.If no timezone is specified, it defaults to UTC.iso_datetime_nowbuilds onaware_datetime_nowand delivers the current datetime in ISO 8601 string format.The module also features aTimerclass, a versatile tool to measure elapsed time. It provides simple methods likeclickto start or mark time,readto read the elapsed time, andresetto start anew. TheTimerclass is also designed as a context manager, which allows it to be used efficiently within with statements.These utilities make thepyassorted.datetimemodule a versatile tool for managing and measuring time in your Python applications.aware_datetime_nowfrompyassorted.datetimeimportaware_datetime_now,iso_datetime_nowprint(aware_datetime_now())# datetime.datetimeprint(iso_datetime_now())# Datetime ISO StringTimerimporttimefrompyassorted.datetimeimportTimertimer=Timer()timer.click()time.sleep(1)timer.click()print(round(timer.read()))# 1withtimer:time.sleep(1)print(round(timer.read()))# 1pyassorted.io.watchThepyassorted.io.watchmodule provides functionality to monitor files for changes. It includes two main functions:watchandasync_watch. Thewatchfunction is a synchronous generator that continuously checks for modifications in a specified file and yields the file path whenever changes are detected.Theasync_watchfunction, on the other hand, is an asynchronous generator doing the same but built for asynchronous programming.importasynciofrompyassorted.ioimportasync_watch,watchdefwatch_file(filepath):forfileinwatch(filepath):print("File changed!")asyncdefasync_watch_file(filepath):asyncforfileinasync_watch(filepath):print("File changed!")filepath="modifying_file.txt"watch_file(filepath)async_watch_file(filepath)pyassorted.lockThepyassorted.lockmodule provides a soft file locking mechanism, ensuring that only one process can access a shared resource at a time.Utilizing a lock file for status tracking, it facilitates both synchronous and asynchronous resource protection in multi-threaded and multi-process environments. Key features include adjustable timeouts, lock expiration, and custom lock file naming.This module, compatible with standard and async context managers, can be seamlessly integrated into your project to maintain data consistency in concurrent operations.fromconcurrent.futuresimportThreadPoolExecutorfrompyassorted.lockimportFileLocknumber=0tasks_num=100lock=FileLock()defadd_one():globalnumberwithlock:number+=1withThreadPoolExecutor(max_workers=40)asexecutor:futures=[executor.submit(add_one)for_inrange(tasks_num)]forfutureinfutures:future.result()assertnumber==tasks_num