Saravanan666/pypi-org huggingface dataset:
Package: async-timeout
asyncio-compatible timeout context manager.Usage exampleThe context manager is useful in cases when you want to apply timeout
logic around block of code or in cases whenasyncio.wait_for()is
not suitable. Also it’s much faster thanasyncio.wait_for()becausetimeoutdoesn’t create a new task.Thetimeout(delay, *, loop=None)call returns a context manager
that cancels a block ontimeoutexpiring:from async_timeout import timeout
async with timeout(1.5):
    await inner()Ifinner()is executed faster than in1.5seconds nothing
happens.Otherwiseinner()is cancelled internally by sendingasyncio.CancelledErrorinto butasyncio.TimeoutErroris
raised outside of context manager scope.timeoutparameter could beNonefor skipping timeout functionality.Alternatively,timeout_at(when)can be used for scheduling
at the absolute time:loop = asyncio.get_event_loop()
now = loop.time()

async with timeout_at(now + 1.5):
    await inner()Please note: it is not POSIX time but a time with
undefined starting base, e.g. the time of the system power on.Context manager has.expiredproperty for check if timeout happens
exactly in context manager:async with timeout(1.5) as cm:
    await inner()
print(cm.expired)The property isTrueifinner()execution is cancelled by
timeout context manager.Ifinner()call explicitly raisesTimeoutErrorcm.expiredisFalse.The scheduled deadline time is available as.deadlineproperty:async with timeout(1.5) as cm:
    cm.deadlineNot finished yet timeout can be rescheduled byshift_by()orshift_to()methods:async with timeout(1.5) as cm:
    cm.shift(1)  # add another second on waiting
    cm.update(loop.time() + 5)  # reschedule to now+5 secondsRescheduling is forbidden if the timeout is expired or after exit fromasync withcode block.Installation$ pip install async-timeoutThe library is Python 3 only!Authors and LicenseThe module is written by Andrew Svetlov.It’sApache 2licensed and freely available.
Package: async-timer
Async timerThis package provides an async timer object, that should have been part of batteries.PurposeSometimes, you need a way to make something happen over and over again at certain times, like updating information or sending reminders. That's where Async Timer comes in. It lets you set up these repeated actions easily.This package is particularly useful for tasks like automatically updating caches in the background without disrupting the primary application's workflow.FeaturesZero Dependencies: Written entirely in Python, Async Timer operates independently without needing any external libraries.Versatility in Callables: It accommodates various callable types, including:Synchronous functionsAsynchronous functionsSynchronous generatorsAsynchronous generatorsWait for the Next Tick: You can set it up so your program waits for the timer to do its thing, and then continues.Keep Getting Updates: You can use it in a loop to keep getting updates every time the timer goes off.Cancel anytime: The timer object can be stopped at any time either explicitly by callingstop()/cancel()method OR it can stop automatically on an awaitable resolving (thecancel_awsconstructor artument)Test friendly: The package provides an additionalmock_async_timer.MockTimerclass with mocked sleep function to aid in your testingExample UsageFastAPIThis snippet starts fastapi webserver with therefresh_dbfunction being executed every 5 seconds, refresing a sharedDB_CACHEobject.importcontextlibimporttimeimportuvicornfromfastapiimportFastAPIimportasync_timerDB_CACHE={"initialised":False}asyncdefrefresh_db():globalDB_CACHEDB_CACHE|={"initialised":True,"cur_value":time.time()}@contextlib.asynccontextmanagerasyncdeflifespan(_app:FastAPI):asyncwithasync_timer.Timer(delay=5,target=refresh_db)astimer:awaittimer.wait(hit_count=1)# block until the timer triggers at least onceyieldapp=FastAPI(lifespan=lifespan)@app.get("/")asyncdefroot():return{"message":"Hello World","db_cache":DB_CACHE}if__name__=="__main__":uvicorn.run(app,host="0.0.0.0",port=8000)join()importasync_timertimer=async_timer.Timer(12,target=lambda:42)timer.start()val=awaittimer.join()# `val` will be set to 42 after 12 secondsfor loop# Async for loop exampleimportasync_timerimporttimewithasync_timer.Timer(14,target=time.time)astimer:asyncfortime_rvintimer:print(f"{time_rv=}")# Prints current time every 14 seconds
Package: async-tio
Async-TioThis is a simple unofficial async Api-wrapper fortio.runInstallation$py-mpipinstallasync_tioInstall Latest$py-mpipinstallgit+https://github.com/Tom-the-Bomb/async-tio.gitExample# assuming you are already inside an async environment and have already imported everything# to instantiate# recommended to have a global class if you are going to run .execute more than 1 time throughout the program# alternatively you can use the async context manager if it's a one time use:# async with async_tio.Tio() as tio: ...tio=async_tio.Tio()# Optional 'loop' and 'session' kwargs etc. if needed# to executeoutput=awaittio.execute("print('')",language="python3")# pass in other optional kwargs if neededprint(str(output))# the formatted output along with the statsprint(output.stdout)# the output by itselfprint(int(output))# returns the exit status# print(vars(output).keys())# -> dict_keys(['token', 'output', 'stdout', 'real_time', 'user_time', 'sys_time', 'cpu_usage', 'exit_status'])# all the attributes of the response object you can access
Package: asynctk
# AsyncTK[![Licence: GPL v3](https://img.shields.io/badge/Licence-GPL%20v3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)## What is AsyncTK?AsyncTK is an asynchronous wrapper for TK/TCL using TKInter and AsyncIO.
It can:Initialise and start the event loopRun all major TK/TCL commands and widgets, asynchronously!Be combined, using class inheritance, with other asynchronous processes and classes!### InstallationAsyncTK can be installed usingpip install asynctk, or for the more adventurous,pip install git+https://github.com/Starwort/asynctk.git### UsageAsyncTK’s window is used as TK’s is, it’s created, and components are placed onto it. Finally, the app’s.mainloop()method is called, and your program runs. Nothing new there, right? Wrong. By callingasyncio.ensure_future()on your coroutines, those coroutines will continue to run, and can interact with the TK window. This means no morethreadingsolutions - processes can change the window!### Future improvementsMake coroutines the default for callbacksEnsure there is no widget lagSubmodulesStability
Package: asynctkinter
AsyncTkinterYoutubeasynctkinteris an async library that saves you from ugly callback-based code,
like most of async libraries do.
Let's say you want to do:print('A')wait for 1secprint('B')wait for a label to be pressedprint('C')in that order.
Your code would look like this:defwhat_you_want_to_do(label):bind_id=Noneprint('A')defone_sec_later(__):nonlocalbind_idprint('B')bind_id=label.bind('<Button>',on_press,'+')label.after(1000,one_sec_later)defon_press(event):label.unbind('<Button>',bind_id)print('C')what_you_want_to_do(...)It's barely readable and not easy to understand.
If you useasynctkinter, the above code will be:importasynctkinterasatasyncdefwhat_you_want_to_do(label):print('A')awaitat.sleep(label.after,1000)print('B')awaitat.event(label,'<Button>')print('C')at.start(what_you_want_to_do(...))InstallationIt's recommended to pin the minor version, because if
it changed, it means someimportantbreaking changes occurred.poetry add asynctkinter@~0.3
pip install "asynctkinter>=0.3,<0.4"UsagefromfunctoolsimportpartialfromtkinterimportTk,Labelimportasynctkinterasatat.install()root=Tk()label=Label(root,text='Hello',font=('',60))label.pack()asyncdefasync_fn(label):sleep=partial(at.sleep,label.after)# wait for 2secawaitsleep(2000)# wait for a label to be pressedevent=awaitat.event(label,'<Button>')print(f"pos:{event.x},{event.y}")# wait until EITHER a label is pressed OR 5sec passes.# i.e. wait at most 5 seconds for a label to be pressed.tasks=awaitat.wait_any(at.event(label,'<Button>'),sleep(5000),)iftasks[0].finished:event=tasks[0].resultprint(f"The label was pressed. (pos:{event.x},{event.y})")else:print("5sec passed")# wait until a label is pressed AND 5sec passes.tasks=awaitat.wait_all(at.event(label,'<Button>'),sleep(5000),)at.start(async_fn(label))root.mainloop()threadingasynctkinterdoesn't have any I/O primitives like Trio and asyncio do,
thus threads are the only way to perform them without blocking the main-thread:fromconcurrent.futuresimportThreadPoolExecuterimportasynctkinterasatexecuter=ThreadPoolExecuter()asyncdefasync_fn(widget):# create a new thread, run a function inside it, then# wait for the completion of that threadr=awaitat.run_in_thread(thread_blocking_operation,after=widget.after)print("return value:",r)# run a function inside a ThreadPoolExecuter, and wait for its completion.# (ProcessPoolExecuter is not supported)r=awaitat.run_in_executer(executer,thread_blocking_operation,after=widget.after)print("return value:",r)Exceptions(not BaseExceptions) are propagated to the caller,
so you can catch them like you do in synchronous code:importrequestsimportasynctkinterasatasyncdefasync_fn(widget):try:r=awaitat.run_in_thread(lambda:requests.get('htt...',timeout=10),after=widget.after)exceptrequests.Timeout:print("TIMEOUT!")else:print('RECEIVED:',r)NoteYou may want to read theasyncgui's documentationas it is the foundation of this library.
Package: async-tkinter-loop
Asynchronous Tkinter MainloopImplementation of asynchronousmainloopfor tkinter, the use of which allows usingasynchandler functions.
It is intended to be as simple to use as possible. No fancy unusual syntax or constructions - just use an alternative
function instead ofroot.mainloop()and wrap asynchronous handlers into a helper function.NotePlease, fill free toreport bugs, addpull requestsorshare your thoughts / ask questions, etc.about the module.Based on ideas from:my answer on ru.stackoverflow.com:https://ru.stackoverflow.com/a/1043146answer ofTerry Jan Reedyon stackoverflow.com:https://stackoverflow.com/a/47896365answer ofjfson ru.stackoverflow.com:https://ru.stackoverflow.com/a/804609InstallationInstall the package with the following command:pip install async-tkinter-looporpip install async-tkinter-loop[examples][examples]part is needed to install optional dependencies (such ashttpxandpillow) to run some of the
examples. If you're not going to run examples, remove the[examples]part from the commandUsepip3instead ofpipon Linux systems to install the package for python3 (not python2)Probably you'll want to create a virtual environment for experiments with this library, but this is optional.If you want to try examples, download the entire repository as an archive (green "code" button onthe GitHub page→
"Download ZIP"), unpack, run any example (of course, you need to install optional dependencies)Some examplesBasic example:importasyncioimporttkinterastkfromasync_tkinter_loopimportasync_handler,async_mainloopasyncdefcounter():i=0whileTrue:i+=1label.config(text=str(i))awaitasyncio.sleep(1.0)root=tk.Tk()label=tk.Label(root)label.pack()tk.Button(root,text="Start",command=async_handler(counter)).pack()async_mainloop(root)Also,async_handlerfunction can be used as a decorator (but it makes a decorated function syncroneous):importasyncioimporttkinterastkfromasync_tkinter_loopimportasync_handler,async_mainloop@async_handlerasyncdefcounter():i=0whileTrue:i+=1label.config(text=str(i))awaitasyncio.sleep(1.0)root=tk.Tk()label=tk.Label(root)label.pack()tk.Button(root,text="Start",command=counter).pack()async_mainloop(root)A more practical example, downloading an image from the Internet withhttpx(you can useaiohttpas well)
and displaying it in the Tkinter window:importtkinterastkfromioimportBytesIOimporthttpxfromPILimportImage,ImageTkfromasync_tkinter_loopimportasync_handler,async_mainloopasyncdefload_image(url):button.config(state=tk.DISABLED)label.config(text="Loading...",image="")asyncwithhttpx.AsyncClient()asclient:response=awaitclient.get(url,follow_redirects=True)ifresponse.status_code!=200:label.config(text=f"HTTP error{response.status_code}")else:content=response.contentpil_image=Image.open(BytesIO(content))image=ImageTk.PhotoImage(pil_image)label.image=imagelabel.config(image=image,text="")button.config(state=tk.NORMAL)url="https://picsum.photos/800/640"root=tk.Tk()root.geometry("800x640")button=tk.Button(root,text="Load an image",command=async_handler(load_image,url))button.pack()label=tk.Label(root)label.pack(expand=1,fill=tk.BOTH)async_mainloop(root)More examples see in theexamplesdirectory.
Package: asynctmdb
ContentsMethodsACCOUNTAUTHENTICATIONCERTIFICATIONSCHANGESCOLLECTIONSCOMPANIESCONFIGURATIONCREDITSDISCOVERFINDGENRESGUEST SESSIONSJOBSKEYWORDSLISTSMOVIESNETWORKSPEOPLEREVIEWSSEARCHTIMEZONESTVTV SEASONSTV EPISODESRunning testsMethodsIn what follows“✔” mark means that method is supported,
but not covered with tests (or not completely covered),“✘” mark means that method is supported
and covered with tests.ACCOUNTGet DetailsGet Created ListsGet Favorite MoviesGet Favorite TV ShowsMark as FavoriteGet Rated MoviesGet Rated TV ShowsGet Rated TV EpisodesGet Movie WatchlistGet TV Show WatchlistAdd to WatchlistAUTHENTICATION✘Create Request Token✘Create Session✘Create Session With Login (do not use)✘Create Guest SessionCERTIFICATIONSGet Movie CertificationsGet TV CertificationsCHANGESGet Movie Change ListGet TV Change ListGet Person Change ListCOLLECTIONSGet DetailsGet ImagesCOMPANIESGet DetailsGet MoviesCONFIGURATIONGet API ConfigurationCREDITSGet DetailsDISCOVERMovie DiscoverTV DiscoverFIND✘Find by IDGENRES✘Get Movie List✘Get TV ListGet MoviesGUEST SESSIONSGet Rated MoviesGet Rated TV ShowsGet Rated TV EpisodesJOBSGet JobsKEYWORDSGet DetailsGet MoviesLISTSv4 or v3 lists?Get DetailsCheck Item StatusCreate ListAdd MovieRemove MovieClear ListDelete ListMOVIES✘Get Details✘Get Account States✘Get Alternative Titles✘Get Changes✘Get Credits✘Get Images✘Get Keywords✘Get Release Dates✘Get Videos✘Get Translations✘Get Recommendations✘Get Similar Movies✘Get Reviews✘Get Lists✘Rate Movie✘Delete Rating✘Get Latest✘Get Now Playing✘Get Popular✘Get Top Rated✘Get UpcomingNETWORKSGet DetailsPEOPLEGet DetailsGet Movie CreditsGet TV CreditsGet Combined CreditsGet External IDsGet ImagesGet Tagged ImagesGet ChangesGet LatestGet PopularREVIEWSGet DetailsSEARCHSearch CompaniesSearch CollectionsSearch KeywordsSearch MoviesMulti SearchSearch PeopleSearch TV ShowsTIMEZONESGet ListTVGet DetailsGet Account StatesGet Alternative TitlesGet ChangesGet Content RatingsGet CreditsGet External IDsGet ImagesGet KeywordsGet RecommendationsGet Similar TV ShowsGet TranslationsGet VideosRate TV ShowDelete RatingGet LatestGet TV Airing TodayGet TV On The AirGet PopularGet Top RatedTV SEASONSGet DetailsGet ChangesGet Account StatesGet CreditsGet External IDsGet ImagesGet VideosTV EPISODESGet DetailsGet ChangesGet Account StatesGet CreditsGet TV Episode External IDsGet ImagesRate TV EpisodeDelete RatingGet VideosRunning testsMake sure that next files are presented in project’s directory:keywithTMDbAPI key (instructions),
e.g.c15d35806311efebcecd5faabe7eaffcloginwithTMDblogin info (user name & password separated by newline),
e.g.johndoe
youwillneverguessPlain./set-api-key.sh./set-login.shpython3.5setup.pytestInsideDockercontainer./set-env.shdocker-composeup
Package: asynctnt-queue
asynctnt-queue is a python/asyncio bindings library fortarantool-queuepackage inTarantool Database, integrated withasynctntmodule.DocumentationDocumentation is availablehere.InstallationUse pip to install:$pipinstallasynctnt-queueBasic UsageTarantool config:box.cfg{listen='127.0.0.1:3301'}box.once('v1',function()box.schema.user.grant('guest','read,write,execute','universe')end)queue=require('queue')queue.create_tube('test_tube','fifottl')Python code:importasyncioimportasynctntimportasynctnt_queueasyncdefrun():conn=asynctnt.Connection(host='127.0.0.1',port=3301)awaitconn.connect()queue=asynctnt_queue.Queue(conn)test_tube=queue.tube('test_tube')# Add a task to queuetask=awaittest_tube.put({'key':'value'})print('Task id:{}'.format(task.task_id))print('Task status:{}'.format(task.status))# Retrieve a task from queuetask=awaittest_tube.take(1)# ... do some work with taskawaittask.ack()awaitconn.disconnect()loop=asyncio.get_event_loop()loop.run_until_complete(run())ReferencesTarantool- in-memory database and
application server.asynctnt- fast
Tarantool database connector for Python/asyncioaiotarantool-
alternative Python/asyncio connector
Package: asynctools
AsyncToolsAsync Tools for Python.Table of ContentsThreadingAsyncParallelPoolThreadingThreading is the most simple thing, but because ofGILit's useless for computation.
Only use when you want to parallelize the access to a blocking resource, e.g. network.AsyncSource:asynctools/threading/Async.pyDecorator for functions that should be run in a separate thread.
When the function is called, it returns athreading.Event.fromasynctools.threadingimportAsync@Asyncdefrequest(url):# ... do requestrequest('http://example.com')# Async requestrequest('http://example.com').wait()# wait for it to completeIf you want to wait for multiple threads to complete, see next chapters.ParallelSource:asynctools/threading/Parallel.pyExecute functions in parallel and collect results.
Each function is executed in its own thread, all threads exit immediately.Methods:__call__(*args, **kwargs): Add a job. Call theParallelobject so it calls the worker function with the same argumentsmap(jobs): Convenience method to call the worker for every argumentfirst(timeout=None): Wait for a single result to be available, with an optional timeout in seconds. The result is returned as soon as it's ready.
If all threads fail with an error --Noneis returned.join(): Wait for all tasks to be finished, and return two lists:A list of resultsA list of exceptionsExample:fromasynctools.threadingimportParalleldefrequest(url):# ... do requestreturndata# Executepll=Parallel(request)forurlinlinks:pll(url)# Starts a new thread# Wait for the resultsresults,errors=pll.join()Since the request method takes just one argument, this can be chained:results,errors=Parallel(request).map(links).join()PoolSource:asynctools/threading/Pool.pyCreate a pool of threads and execute work in it.
Useful if you do want to launch a limited number of long-living threads.Methods are same withParallel, with some additions:__call__(*args, **kwargs)map(jobs)first(timeout=None)close(): Terminate all threads. The pool is no more usable when closed.__enter__,__exit__context manager to be used withwithstatementExample:fromasynctools.threadingimportPooldefrequest(url):# ... do long requestreturndata# Make poolpool=Pool(request,5)# Assign some jobforurlinlinks:pll(url)# Runs in a pool# Wait for the resultsresults,errors=pll.join()
Package: async-to-sync
Convert async coroutine functions to normal ones.Installation$pipinstallasync_to_syncUsageimportasync_to_syncassync# an async object method to demonstrate useclassasync_class:asyncdefsum(self,a,b):returna+basync_object=async_class()# wrap all async methods of an objectsync_object=sync.methods(async_object)assertsync_object.sum(1,2)==3# wrap a single async callablesync_function=sync.function(async_object.sum)assertsync_function(4,5)==9# wait for a coroutinesync_result=sync.coroutine(async_object.sum(6,7))assertsync_result==13# manually stop default event loopsync.stop()# manually start default event loopsync.start()
Package: asynctradier
asynctradierAsync api wrapper forTradier.This isNOTan official package of Tradier.Installpip install asynctradierif your are using poetrypoetry add asynctradierDocumentationRead The DocSupported APIAccount:white_check_mark: Get User Profile:white_check_mark: Get Balances:white_check_mark: Get Positions:white_check_mark: Get History:white_check_mark: Get Gain/Loss:white_check_mark: Get Orders:white_check_mark: Get an OrderTrading:white_check_mark: Modify Order:white_check_mark: Cancel Order:white_check_mark: Place Equity Order:white_check_mark: Place Option Order:white_check_mark: Place Multileg Order:white_square_button: Place Combo Order:white_square_button: Place OTO Order:white_square_button: Place OCO Order:white_square_button: Place OTOCO OrderMarket Data:white_check_mark: Get Quotes:white_check_mark: Get Option Chains:white_check_mark: Get Option Strikes:white_check_mark: Get Option Expirations:white_check_mark: Lookup Option Symbols:white_check_mark: Get Historical Quotes:white_check_mark: Get Time and Sales:white_check_mark: Get ETB Securities:white_square_button: Get Clock:white_check_mark: Get Calendar:white_check_mark: Search Companies:white_check_mark: Lookup SymbolStreaming:white_check_mark: Market WebSocket:white_check_mark: Account WebSocket
Package: async-translate
async_translateMulti-provider async translate APIWhy?Most translate APIs work on one backend (usually Google Translate), and few are fully asynchronous.I wanted a translate API that usesasyncandawait, and I wanted to be able to use multiple providers without having
to deal with their different APIs.I built this to use with my Discord bot,Mr. Translate.InstallationCurrently this uses Python 3.8 specific features.Install withpip install -U async-translate.Optional Default ProvidersA few providers are baked into this package. You can install them with:Azure Cognitive Servicespip install -U async-translate[azure]Google Translatepip install -U async-translate[google]Custom ProvidersSeeCUSTOM_PROVIDERS.mdon making your own providers.Feel free to contribute back to the project with a pull request containing code for other providers.
Package: async-truckersmp
An asynchronous Python API wrapper forTruckersMP.WarningThis library is in alpha and bugs may still be present.FeaturesRate limiting- Pre-emptive rate limiting so you’ll never hit a 429.Caching- Automatic caching of responses so you don’t have to.Configurable- Several configuration options on initialisation.Documented- Full docs with examples included for reference.Data models- API responses are parsed into objects (Python classes).UsageInstallInstall via pip using either of these methods:pip install async-truckersmppip install git+https://github.com/SamNuttall/Async-TruckersMP.gitQuickstartLet’s write a script to print all the server names.fromtruckersmpimportTruckersMP# Import the libraryloop=asyncio.get_event_loop()# Get the asyncio event loopasyncdefmain():truckersmp=TruckersMP()# Initalise the TruckersMP classservers=awaittruckersmp.get_servers()# Call the get_servers methodforserverinservers:# Loop through each serverprint(server.name)# Get the name of the server and print itloop.run_until_complete(main())# Run the main functionResources & SupportDocumentation.Github Repository.If you need further help, feel free to contact Sam#9210 on Discord or open a new issue.LicenceReleased under theMIT License.