Package: quenouille
QuenouilleA library of multithreaded iterator workflows for python.It is typically used to iterate over lazy streams without overflowing memory, all while respecting group parallelism constraints and throttling, e.g. when downloading massive amounts of urls from the web concurrently.It is mainly used by theminetpython library and CLI tool to power its downloaders and crawlers.InstallationYou can installquenouillewith pip using the following command:pip install quenouilleUsageimap, imap_unorderedThreadPoolExecutor#.imap, #.imap_unordered#.shutdownNamedLocksMiscellaneous notesThe None groupParallelism > workersCallable parallelism guaranteesParallelism vs. throttlingAdding entropy to throttleCaveats regarding exception raisingCaveats of using imap with queuesimap, imap_unorderedFunction lazily consuming an iterable and applying the desired function over the yielded items in a multithreaded fashion.This function is also able to respect group constraints regarding parallelism and throttling: for instance, if you need to download urls in a multithreaded fashion and need to ensure that you won't hit the same domain more than twice at the same time, this function can be given proper settings to ensure the desired behavior.The same can be said if you need to make sure to wait for a certain amount of time between two hits on the same domain by using this function's throttling.Finally note that this function comes in two flavors:imap_unordered, which will output processed items as soon as they are done, andimap, which will output items in the same order as the input, at the price of slightly worse performance and an increased memory footprint that depends on the number of items that have been processed before the next item can be yielded.importcsvfromquenouilleimportimap,imap_unordered# Reading urls lazily from a CSV file using a generator:defurls():withopen('urls.csv')asf:reader=csv.DictReader(f)forlineinreader:yieldline['url']# Defining some functionsdeffetch(url):# ... e.g. use urllib3 to download the url# remember this function must be threadsafereturnhtmldefget_domain_name(url):# ... e.g. use ural to extract domain name from urlreturndomain_name# Performing 10 requests at a time:forhtmlinimap(urls(),fetch,10):print(html)# Ouputting results as soon as possible (in arbitrary order)forhtmlinimap_unordered(urls(),fetch,10):print(html)# Ensuring we don't hit the same domain more that twice at a timeforhtmlinimap(urls(),fetch,10,key=get_domain_name,parallelism=2):print(html)# Waiting 5 seconds between each request on a same domainforhtmlinimap(urls(),fetch,10,key=get_domain_name,throttle=5):print(html)# Throttle time depending on domaindefthrottle(group,item,result):ifgroup=='lemonde.fr':return10return2forhtmlinimap(urls(),fetch,10,key=get_domain_name,throttle=throttle):print(html)# Only load 10 urls into memory when attempting to find next suitable jobforhtmlinimap(urls(),fetch,10,key=get_domain_name,throttle=5,buffer_size=10):print(html)Argumentsiterable(iterable): Any python iterable.func(callable): Function used to perform the desired tasks. The function takes an item yielded by the given iterable as single argument. Note that since this function will be dispatched in worker threads, so you should ensure it is thread-safe.threads(int, optional): Maximum number of threads to use. Defaults tomin(32, os.cpu_count() + 1). Note that it can be0, in which case no threads will be used and everything will run synchronously (this can be useful for debugging or to avoid duplicating code sometimes).key(callable, optional): Function returning to which "group" a given item is supposed to belong. This will be used to ensure maximum parallelism is respected.parallelism(int or callable, optional)[1]: Number of threads allowed to work on a same group at once. Can also be a function taking a group and returning its parallelism.buffer_size(int, optional)[1024]: Maximum number of items the function will buffer into memory while attempting to find an item that can be passed to a worker immediately, all while respecting throttling and group parallelism.throttle(int or float or callable, optional): Optional throttle time, in seconds, to wait before processing the next item of a given group. Can also be a function taking last group, item and result and returning next throttle time for this group.block(bool, optional)[False]: Whether to block when using thegetmethod of the given queue.panic(callable, optional): Function that will be called when the process has errored. Useful to unblock some functions and avoid deadlock in specific situations. Note that this function will not be called when synchronous (i.e. when not using additional threads).initializer(callable, optional): Function to run at the start of each thread worker. Can be useful to setupthread-local data, for instance. Remember this function must be threadsafe and should not block because the thread pool will wait for each thread to be correctly booted before being able to proceed. If one of the function calls fails, the thread pool will raise aquenouille.exceptions.BrokenThreadPoolerror and terminate immediately.initargs(iterable, optional): Arguments to pass to theinitializerfunction.wait(bool, optional)[True]: Whether to join worker threads, i.e. wait for them to end, when shutting down the executor. Set this toFalseif you need to go on quickly without waiting for your worker threads to end when cleaning up the executor's resources. Just note that if you spawn other thread-intensive tasks or other executors afterwards in rapid succession, you might start too many threads at once.daemonic(bool, optional)[False]: whether to spawn daemonic worker. If your worker are daemonic, the interpreter will not wait for them to end when exiting. This can be useful, combined towait=False, for instance, if you want your program to exit as soon as hitting ctrl+C (you might want to avoid this if your threads need to cleanup things on exit as they will be abruptly shut down).Using a queue rather than an iterableIf you need to add new items to process as a result of performing tasks (when designing a web crawler for instance, where each downloaded page will yield new pages to explore further down), know that theimapandimap_unorderedfunction also accepts queues as input:fromqueueimportQueuefromquenouilleimportimapjob_queue=Queue()job_queue.put(1)# Enqueuing new jobs in the workerdefworker(i):ifi<3:job_queue.put(i+1)returni*2list(imap(job_queue,worker,2))>>>[2,4,6]# Enqueuing new jobs while iterating over resultsjob_queue=Queue()job_queue.put(1)results=[]foriinimap(job_queue,worker,2):ifi<5:job_queue.put((i/2)+1)results.append(i)results>>>[2,4,6]Note thatimapwill only run until the queue is fully drained. So if you decide to add more items afterwards, this is not the function's concern anymore.ThreadPoolExecutorIf you need to runimaporimap_unorderedmultiple times in succession while keeping the same thread pool up and running, you can also directly use quenouille'sThreadPoolExecutorlike so:fromquenouilleimportThreadPoolExecutor# Using it as a context manager:withThreadPoolExecutor(max_workers=4)asexecutor:foriinexecutor.imap(range(10),worker):print(i)forjinexecutor.imap_unordered(range(10),worker):print(j)# Or if you prefer shutting down the executor explicitly:executor=ThreadPoolExecutor()executor.imap(range(10),worker)executor.shutdown(wait=False)Note that your throttling state is kept between multipleimapandimap_unorderedcalls so you don't end up perform some tasks too soon. But keep in mind this state is tied to thekeyfunction you provide to remain consistent, so if you change the usedkey, the throttling state will be reset.Argumentsmax_workers(int, optional): Maximum number of threads to use. Defaults tomin(32, os.cpu_count() + 1). Note that it can be0, in which case no threads will be used and everything will run synchronously (this can be useful for debugging or to avoid duplicating code sometimes).initializer(callable, optional): Function to run at the start of each thread worker. Can be useful to setupthread-local data, for instance. Remember this function must be threadsafe and should not block because the thread pool will wait for each thread to be correctly booted before being able to proceed. If one of the function calls fails, the thread pool will raise aquenouille.exceptions.BrokenThreadPoolerror and terminate immediately.initargs(iterable, optional): Arguments to pass to theinitializerfunction.wait(bool, optional)[True]: Whether to join worker threads, i.e. wait for them to end, when closing the executor. Set this toFalseif you need to go on quickly without waiting for your worker threads to end when cleaning up the executor's resources. Just note that if you spawn other thread-intensive tasks or other executors afterwards in rapid succession, you might start too many threads at once.daemonic(bool, optional)[False]: whether to spawn daemonic worker. If your worker are daemonic, the interpreter will not wait for them to end when exiting. This can be useful, combined towait=False, for instance, if you want your program to exit as soon as hitting ctrl+C (you might want to avoid this if your threads need to cleanup things on exit as they will be abruptly shut down).#.imap, #.imap_unorderedBasically the same as describedherewith the following arguments:iterable(iterable): Any python iterable.func(callable): Function used to perform the desired tasks. The function takes an item yielded by the given iterable as single argument. Note that since this function will be dispatched in worker threads, so you should ensure it is thread-safe.key(callable, optional): Function returning to which "group" a given item is supposed to belong. This will be used to ensure maximum parallelism is respected.parallelism(int or callable, optional)[1]: Number of threads allowed to work on a same group at once. Can also be a function taking a group and returning its parallelism.buffer_size(int, optional)[1024]: Maximum number of items the function will buffer into memory while attempting to find an item that can be passed to a worker immediately, all while respecting throttling and group parallelism.throttle(int or float or callable, optional): Optional throttle time, in seconds, to wait before processing the next item of a given group. Can also be a function taking last group, item and result and returning next throttle time for this group.block(bool, optional)[False]: Whether to block when using thegetmethod of the given queue.panic(callable, optional): Function that will be called when the process has errored. Useful to unblock some functions and avoid deadlock in specific situations. Note that this function will not be called when synchronous (i.e. when not using additional threads).#.shutdownMethod used to explicitly shutdown the executor.Argumentswait(bool, optional)[True]: Whether to join worker threads, i.e. wait for them to end, when shutting down the executor. Set this toFalseif you need to go on quickly without waiting for your worker threads to end when cleaning up the executor's resources. Just note that if you spawn other thread-intensive tasks or other executors afterwards in rapid succession, you might start too many threads at once.NamedLocksA weakref dictionary of locks useful to make some tasks based on keys threadsafe, e.g. if you need to ensure that two threads will not be writing to the same file at once.fromquenouilleimportNamedLockslocks=NamedLocks()defworker(filename):withlocks[filename]:withopen(filename,'a+')asf:f.write('hello\n')Miscellaneous notesThe None groupTheimapfunctions consider theNonegroup (this can happen if yourkeyfunction returnsNone) as special and will always consider the attached items can be processed right away without parallelism constraints nor throttle.Withoutkey, all items are considered as belonging to theNonegroup.Parallelism > workersIf you setparallelismto10and only allocate5threads to perform your tasks, it should be obvious that the actual parallelism will never reach10.quenouillewon't warn you of this because it might be convenient not to give this too much thought and has not much consequence, but keep this in mind.Callable parallelism guaranteesIf you decide to pass a function to declare a custom parallelism for each group rather than a global fixed one, know that the function will be called each timequenouillehas to make a decision regarding the next items to enqueue so that we don't use any memory to record the information.This means that you should guarantee that the given function is idempotent and will always return the same parallelism for a given group if you don't want to risk a deadlock.Parallelism vs. throttlingIf a group is being trottled, it should be obvious thatquenouillewon't perform more than one single task for this group at once, so itsparallelismis in fact1, in spite of other settings.This does not mean thatparallelismfor some groups andthrottlefor others is impossible. This can be achieved through callables.Adding entropy to throttleYou can understand the callablethrottlekwarg as "what's the minimum time the next job from this group should wait before firing up". This means that if you need to add entropy to the throttle time, you can indeed make this function work with randomness like so:fromrandomimportrandom# Waiting 5 + (between 0 and 2) secondsdefthrottle(group,item,result):return5+(2*random())Caveats regarding exception raisingDeferred generator usage exception deadlocksIf you consume a generator returned byimap/imap_unorderedsomewhere else than where you created it, you may end up in a deadlock if you raise an exception.This is not important when usingdaemonic=Truebut you might stumble upon segfaults on exit because of python reasons beyond my control.# Safeforiteminimap(...):raiseRuntimeError# Not safeit=imap(...)foriteminit:raiseRuntimeErrorIf you really want to do that, because you don't want to use theThreadPoolExecutorcontext manager, you can try using the experimentalexcepthookkwarg:# Probably safeit=imap(...,excepthook=True)foriteminit:raiseRuntimeErrorCaveats of using imap with queuesTypical deadlocksEven ifimapcan process an input queue, you should avoid to find yourself in a situation where adding to the queue might block execution if you don't want to end in a deadlock. It can be easy to footgun yourself if your queue has amaxsize, for instance:fromqueueimportQueuefromquenouilleimportimapjob_queue=Queue(maxsize=2)job_queue.put(1)foriinimap(job_queue,worker):ifi<2:job_queue.put(2)job_queue.put(3)# This will put you in a deadlock because this will block# because of the queue `maxsize` set to 2job_queue.put(4)print(i)Design choicesTo enable you to add items to the queue in the loop body and so it can safely detect when your queue is drained without race condition,quenouilleacknowledges that a task is finished only after what you execute in the loop body is done.This means that sometimes it might be more performant to only add items to the queue from the worker functions rather than from the loop body.queue.task_doneFor now,quenouilledoes not callqueue.task_donefor you, so this remains your responsability, if you want to be able to callqueue.joindown the line.