Tasks 1 0 3

« Leo Folder Locker 2.0 Repair Tasks 3.3 Shoot-n-Scroll 1.30 » Comment Rules & Etiquette - We welcome all comments from our readers, but any comment section requires some moderation. Some posts are auto-moderated to reduce spam, including links and swear words. The tasks attribute is either a list of Tasks, or a Task: int dict, where Task is either a python callable or a TaskSet class. If the task is a normal python function they receive a single argument which is the User instance that is executing the task. Here is an example of a User task declared as a normal python function. If you want to match a pre-release version, the specification must contain a major, minor, patch, and pre-release version from the list above. Examples: 5.x, 5.4.x, 5.3.1, =5.0.0-0. If unspecified, a version will be chosen automatically: checkLatest Always check for new versions. 3 months free with 1-year plan. Norton Secure VPN Best for customer support. Tasks 2.7.1 fixes a number of non-critical bugs in version 2.7 and is a recommended upgrade for all. Download this app from Microsoft Store for Windows 10, Windows 10 Mobile, Windows 10 Team (Surface Hub). See screenshots, read the latest customer reviews, and compare ratings for One Task.

Single n-back task with visual stimuli.

The n-back task is a continuous performance task that is commonly used as an assessment in psychology and cognitive neuroscience to measure a part of working memory and working memory capacity.[1] The n-back was introduced by Wayne Kirchner in 1958.[2] Some researchers have argued that n-back training may increase IQ, but evidence is mixed.[citation needed]

The task[edit]

The subject is presented with a sequence of stimuli, and the task consists of indicating when the current stimulus matches the one from n steps earlier in the sequence. The load factor n can be adjusted to make the task more or less difficult.

To clarify, the visual n-back test is similar to the classic memory game of 'Concentration'. However, instead of different items that are in a fixed location on the game board, there is only one item, that appears in different positions on the game board during each turn. '1-N' means that you have to remember the position of the item, one turn back. '2-N' means that you have to remember the position of the item two turns back, and so on.

For example, an auditory three-back test could consist of the experimenter reading the following list of letters to the test subject:

T L H C H O C Q L C K L H C Q T R R K C H R

The subject is supposed to indicate when the letters marked in bold are read, because those correspond to the letters that were read three steps earlier.

The n-back task captures the active part of working memory. When n equals 2 or more, it is not enough to simply keep a representation of recently presented items in mind; the working memory buffer also needs to be updated continuously to keep track of what the current stimulus must be compared to. To accomplish this task, the subject needs to both maintain and manipulate information in working memory.[1]

Dual n-back[edit]

The dual-taskn-back task is a variation that was proposed by Susanne Jaeggi et al. in 2003.[3] In the dual-task paradigm, two independent sequences are presented simultaneously, typically using different modalities of stimuli, such as one auditory and one visual.

Several smart phone apps and online implementations of the Dual N-Back task exist [4].

Applications[edit]

Assessment[edit]

The n-back task was developed by Wayne Kirchner for his research into short-term memory; he used it to assess age differences in memory tasks of 'rapidly changing information'.[2]

Construct validity[edit]

There is some question about the construct validity of the n-back task. While the task has strong face validity and is now in widespread use as a measure of working memory in clinical and experimental settings, there are few studies which explore the convergent validity of the n-back task with other measures of working memory.[5] Those studies have largely revealed weak or modest correlations between individuals' performance on the n-back task and performance on other standard, accepted assessments of working memory.[5][6]

There are two main hypotheses for this weak correlation between the n-back task and other working memory assessments. One proposal is that the n-back task assesses different 'sub-components' of working memory than do other assessments. A more critical explanation is that rather than primarily assessing working memory, performance on the n-back task depends on 'familiarity- and recognition-based discrimination processes,' whereas valid assessments of working memory demand 'active recall.'[6] Whatever the cause of the performance differences between the n-back and other assessments of working memory, some researchers stress the need for further exploration of the construct validity of the n-back task.[5]

Performance on the n-back task seems to be more closely correlated with performance on measures of fluid intelligence than it is with performance on other measures of working memory (which is also correlated with performance on measures of fluid intelligence).[6] In the same vein, training on the n-back task appears to improve performance on subsequent fluid intelligence assessments, especially when the training is at a higher n-value.[6]

Treatment[edit]

A 2008 research paper claimed that practicing a dual n-back task can increase fluid intelligence (Gf), as measured in several different standard tests.[7] This finding received some attention from popular media, including an article in Wired.[8] However, a subsequent criticism of the paper's methodology questioned the experiment's validity and took issue with the lack of uniformity in the tests used to evaluate the control and test groups.[9] For example, the progressive nature of Raven's Advanced Progressive Matrices (APM) test may have been compromised by modifications of time restrictions (i.e., 10 minutes were allowed to complete a normally 45-minute test). The authors of the original paper later addressed this criticism by citing research indicating that scores in timed administrations of the APM are predictive of scores in untimed administrations.[10]

The 2008 study was replicated in 2010 with results indicating that practicing single n-back may be almost equal to dual n-back in increasing the score on tests measuring Gf (fluid intelligence). The single n-back test used was the visual test, leaving out the audio test.[10] In 2011, the same authors showed long-lasting transfer effect in some conditions.[11]

Two studies published in 2012 failed to reproduce the effect of dual n-back training on fluid intelligence. These studies found that the effects of training did not transfer to any other cognitive ability tests.[12][13] In 2014, a meta-analysis of twenty studies showed that n-back training has small but significant effect on Gf and improve it on average for an equivalent of 3-4 points of IQ.[14] In January 2015, this meta-analysis was the subject of a critical review due to small-study effects.[15]

A more recent and extended meta-analysis in January 2017[16] also found that n-back training produces a medium improvement in unrelated n-back training tasks, but a small improvement in unrelated working memory (WM) tasks:

The present meta-analysis on the efficacy of n-back training shows medium transfer effects to untrained versions of the trained n-back tasks and small transfer effects to other WM tasks, cognitive control, and Gf [fluid intelligence]. Our results suggest that previous meta-analyses investigating the effects of WM training have overestimated the transfer effects to WM by including untrained variants of the training tasks in their WM transfer domain. Consequently, transfer of n-back training is more task-specific than has previously been suggested.

The question of whether n-back training produces real-world improvements to working memory remains controversial.[17]

Use in tutoring and rehabilitation[edit]

The n-back is now in use outside experimental, clinical, and medical settings. Tutoring companies utilize versions of the task (in conjunction with other cognitive tasks) to allegedly improve the fluid intelligence of their clients.[18] Tutoring companies and psychologists also utilize the task to improve the focus of individuals with ADHD[18] and to rehabilitate sufferers of traumatic brain injury;[19] experiments have found evidence that practice with the task helps these individuals focus for up to eight months following training.[19] However, much debate remains about whether training on the n-back and similar tasks can improve performance in the long run or whether the effects of training are transient,[18][19] and if the effects of training n-back generalize to general cognitive processing, for instance, to fluid intelligence.[20] Despite the claims of commercial providers, there are some researchers who question whether the results of memory training are transferable. Researchers from the University of Oslo published results of the meta-analytical review analyzing various studies on memory training techniques (including n-back) and concluded that 'training programs give only near-transfer effects, and there is no convincing evidence that even such near-transfer effects are durable.'[21]

Neurobiology of n-back task[edit]

Meta-analysis of 24 n-back neuroimaging studies have shown that during this task the following brain regions are consistently activated: lateral premotor cortex; dorsal cingulate and medial premotor cortex; dorsolateral and ventrolateral prefrontal cortex; frontal poles; and medial and lateral posterior parietal cortex.[22]

See also[edit]

References[edit]

  1. ^ abGazzaniga, Michael S.; Ivry, Richard B.; Mangun, George R. (2009). Cognitive Neuroscience: The Biology of the Mind (2nd ed.).
  2. ^ abKirchner, W. K. (1958). 'Age differences in short-term retention of rapidly changing information'. Journal of Experimental Psychology. 55 (4): 352–358. doi:10.1037/h0043688. PMID13539317.
  3. ^Jaeggi, S. M., Seewer, R., Nirkko, A. C., Eckstein, D., Schroth, G., Groner, R., et al., (2003). Does excessive memory load attenuate activation in the prefrontal cortex? Load-dependent processing in single and dual tasks: functional magnetic resonance imaging study, Neuroimage 19(2) 210-225.
  4. ^Roizen, Michael; Oz, Mehmet (2018-01-12). 'Playing brain games may help sharpen your skills'. Houston Chronicle. Hearst. Retrieved 10 November 2018.
  5. ^ abcKane, M.J., Conway, A.R.A, Miura, T.K., & Colflesh, G.J.H (2007). 'Working memory, attention control, and the N-back task: a question of construct validity'(PDF). Journal of Experimental Psychology: Learning, Memory, and Cognition. 33 (3): 615–622. doi:10.1037/0278-7393.33.3.615. PMID17470009.CS1 maint: multiple names: authors list (link)
  6. ^ abcdJaeggi, S.M., Buschkuehl, M., Perrig, W.J., & Meier, B. (2010). 'The concurrent validity of the N-back task as a working memory measure'. Memory. 18 (4): 394–412. doi:10.1080/09658211003702171. PMID20408039. S2CID42767249.CS1 maint: multiple names: authors list (link)
  7. ^Jaeggi, S. M., Buschkuehl, M., Jonides, J., Perrig, W. J. (2008),Improving fluid intelligence with training on working memory, Proceedings of the National Academy of Sciences, vol. 105 no. 19
  8. ^Alexis Madrigal, Forget Brain Age: Researchers Develop Software That Makes You Smarter, Wired, April 2008
  9. ^Moody, D. E. (2009). 'Can intelligence be increased by training on a task of working memory?'. Intelligence. 37 (4): 327–328. doi:10.1016/j.intell.2009.04.005.
  10. ^ abJaeggi, Susanne M.; Studer-Luethi, Barbara; Buschkuehl, Martin; Su, Yi-Fen; Jonides, John; Perrig, Walter J. (2010). 'The relationship between n-back performance and matrix reasoning -- implications for training and transfer'. Intelligence. 38 (6): 625–635. doi:10.1016/j.intell.2010.09.001. ISSN0160-2896.
  11. ^Jaeggi, Susanne; et al. (2011). 'Short- and long-term benefits of cognitive training'. PNAS. 108 (25): 10081–10086. Bibcode:2011PNAS..10810081J. doi:10.1073/pnas.1103228108. PMC3121868. PMID21670271.
  12. ^Redick, T. S.; Shipstead, Z.; Harrison, T. L.; Hicks, K. L.; Fried, D. E.; Hambrick, D. Z.; Kane, M. J.; Engle, R. W. (2012). 'No Evidence of Intelligence Improvement After Working Memory Training: A Randomized, Placebo-Controlled Study'. Journal of Experimental Psychology: General. 142 (2): 359–379. doi:10.1037/a0029082. PMID22708717. S2CID15117431.
  13. ^Chooi, W. T.; Thompson, L. A. (2012). 'Working memory training does not improve intelligence in healthy young adults'. Intelligence. 40 (6): 531–542. doi:10.1016/j.intell.2012.07.004.
  14. ^Au, Jacky; et al. (2014). 'Improving fluid intelligence with training on working memory: a meta-analysis'(PDF). Psychonomic Bulletin & Review. 22 (2): 366–377. doi:10.3758/s13423-014-0699-x. PMID25102926.
  15. ^Bogg, Tim; Lasecki, Leanne (22 January 2015). 'Reliable gains? Evidence for substantially underpowered designs in studies of working memory training transfer to fluid intelligence'. Frontiers in Psychology. 5: 1589. doi:10.3389/fpsyg.2014.01589. PMC4010796. PMID25657629.
  16. ^Soveri, Anna; Antfolk, Jan; Karlsson, Linda; Salo, Benny; Laine, Matti (1 August 2017). 'Working memory training revisited: A multi-level meta-analysis of n-back training studies'. Psychonomic Bulletin & Review. 24 (4): 1077–1096. doi:10.3758/s13423-016-1217-0. ISSN1531-5320. Retrieved 6 September 2020.
  17. ^Soveri, Anna; Antfolk, Jan; Karlsson, Linda; Salo, Benny; Laine, Matti (1 August 2017). 'Working memory training revisited: A multi-level meta-analysis of n-back training studies'. Psychonomic Bulletin & Review. 24 (4): 1077–1096. doi:10.3758/s13423-016-1217-0. ISSN1531-5320. Retrieved 6 September 2020.
  18. ^ abcHurley, Dan (2012-10-31). 'The Brain Trainers'. The New York Times. Retrieved 9 November 2012.
  19. ^ abcHurley, Dan (2012-04-18). 'Can You Make Yourself Smarter?'. The New York Times. Retrieved 9 November 2012.
  20. ^Daniel Willingham (2012-06-19). 'New study: Fluid intelligence not trainable'. Retrieved 2013-04-22.
  21. ^Monica Melby-Lervåg & Charles Hulme (2013). 'Is Working Memory Training Effective? A Meta-Analytic Review'(PDF). Developmental Psychology. 49 (2): 270–291. doi:10.1037/a0028228. PMID22612437.
  22. ^Owen, Adrian M.; McMillan, Kathryn M.; Laird, Angela R.; Bullmore, Ed (2005). 'N-back working memory paradigm: A meta-analysis of normative functional neuroimaging studies'. Human Brain Mapping. 25 (1): 46–59. doi:10.1002/hbm.20131. PMC6871745. PMID15846822.

External links[edit]

  • Brain Workshop, an open-source, free, standalone, multi-platform implementation of the n-back task
  • IQ boost, a dual n-back application for iOS
  • Brain N-Back, an n-back task implemented as an Android app
  • Dual-N-Back.io, Dual N-back task, implemented as an open source progressive web application. Can be played in a browser, or cached for offline use on mobile.
  • Dual N-Back Meta-analysis showing medium effect of transfer training to fluid intelligence
Retrieved from 'https://en.wikipedia.org/w/index.php?title=N-back&oldid=984457795'

This section outlines high-level asyncio APIs to work with coroutinesand Tasks.

Coroutines declared with the async/await syntax is thepreferred way of writing asyncio applications. For example, the followingsnippet of code (requires Python 3.7+) prints “hello”, waits 1 second,and then prints “world”:

Note that simply calling a coroutine will not schedule it tobe executed:

To actually run a coroutine, asyncio provides three main mechanisms:

  • The asyncio.run() function to run the top-levelentry point “main()” function (see the above example.)

  • Awaiting on a coroutine. The following snippet of code willprint “hello” after waiting for 1 second, and then print “world”after waiting for another 2 seconds:

    Expected output:

  • The asyncio.create_task() function to run coroutinesconcurrently as asyncio Tasks.

    Let’s modify the above example and run two say_after coroutinesconcurrently:

    Note that expected output now shows that the snippet runs1 second faster than before:

We say that an object is an awaitable object if it can be usedin an await expression. Many asyncio APIs are designed toaccept awaitables.

There are three main types of awaitable objects:coroutines, Tasks, and Futures.

Coroutines

Python coroutines are awaitables and therefore can be awaited fromother coroutines:

Important

In this documentation the term “coroutine” can be used fortwo closely related concepts:

  • a coroutine function: an asyncdef function;

  • a coroutine object: an object returned by calling acoroutine function.

asyncio also supports legacy generator-based coroutines.

Tasks

Tasks are used to schedule coroutines concurrently.

When a coroutine is wrapped into a Task with functions likeasyncio.create_task() the coroutine is automaticallyscheduled to run soon:

Futures

A Future is a special low-level awaitable object thatrepresents an eventual result of an asynchronous operation.

When a Future object is awaited it means that the coroutine willwait until the Future is resolved in some other place.

Future objects in asyncio are needed to allow callback-based codeto be used with async/await.

Normally there is no need to create Future objects at theapplication level code.

Future objects, sometimes exposed by libraries and some asyncioAPIs, can be awaited:

A good example of a low-level function that returns a Future objectis loop.run_in_executor().

asyncio.run(coro, *, debug=False)

Execute the coroutinecoro and return the result.

This function runs the passed coroutine, taking care ofmanaging the asyncio event loop, finalizing asynchronousgenerators, and closing the threadpool.

This function cannot be called when another asyncio event loop isrunning in the same thread.

If debug is True, the event loop will be run in debug mode.

This function always creates a new event loop and closes it atthe end. It should be used as a main entry point for asyncioprograms, and should ideally only be called once.

Example:

New in version 3.7.

Changed in version 3.9: Updated to use loop.shutdown_default_executor().

Note

The source code for asyncio.run() can be found inLib/asyncio/runners.py.

asyncio.create_task(coro, *, name=None)

Wrap the corocoroutine into a Taskand schedule its execution. Return the Task object.

If name is not None, it is set as the name of the task usingTask.set_name().

The task is executed in the loop returned by get_running_loop(),RuntimeError is raised if there is no running loop incurrent thread.

This function has been added in Python 3.7. Prior toPython 3.7, the low-level asyncio.ensure_future() functioncan be used instead:

New in version 3.7.

coroutine asyncio.sleep(delay, result=None, *, loop=None)

Block for delay seconds.

If result is provided, it is returned to the callerwhen the coroutine completes.

sleep() always suspends the current task, allowing other tasksto run.

Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.

Example of coroutine displaying the current date every secondfor 5 seconds:

awaitable asyncio.gather(*aws, loop=None, return_exceptions=False)

Run awaitable objects in the awssequence concurrently.

If any awaitable in aws is a coroutine, it is automaticallyscheduled as a Task.

If all awaitables are completed successfully, the result is anaggregate list of returned values. The order of result valuescorresponds to the order of awaitables in aws.

If return_exceptions is False (default), the firstraised exception is immediately propagated to the task thatawaits on gather(). Other awaitables in the aws sequencewon’t be cancelled and will continue to run.

If return_exceptions is True, exceptions are treated thesame as successful results, and aggregated in the result list.

If gather() is cancelled, all submitted awaitables(that have not completed yet) are also cancelled.

If any Task or Future from the aws sequence is cancelled, it istreated as if it raised CancelledError – the gather()call is not cancelled in this case. This is to prevent thecancellation of one submitted Task/Future to cause otherTasks/Futures to be cancelled.

Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.

Example:

Note

If return_exceptions is False, cancelling gather() after ithas been marked done won’t cancel any submitted awaitables.For instance, gather can be marked done after propagating anexception to the caller, therefore, calling gather.cancel()after catching an exception (raised by one of the awaitables) fromgather won’t cancel any other awaitables.

Changed in version 3.7: If the gather itself is cancelled, the cancellation ispropagated regardless of return_exceptions.

awaitable asyncio.shield(aw, *, loop=None)

Protect an awaitable objectfrom being cancelled.

If aw is a coroutine it is automatically scheduled as a Task.

The statement:

is equivalent to:

except that if the coroutine containing it is cancelled, theTask running in something() is not cancelled. From the pointof view of something(), the cancellation did not happen.Although its caller is still cancelled, so the “await” expressionstill raises a CancelledError.

Tasks 1 0 3 0

If something() is cancelled by other means (i.e. from withinitself) that would also cancel shield().

If it is desired to completely ignore cancellation (not recommended)the shield() function should be combined with a try/exceptclause, as follows:

Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.

coroutine asyncio.wait_for(aw, timeout, *, loop=None)

Wait for the awawaitableto complete with a timeout.

If aw is a coroutine it is automatically scheduled as a Task.

timeout can either be None or a float or int number of secondsto wait for. If timeout is None, block until the futurecompletes.

If a timeout occurs, it cancels the task and raisesasyncio.TimeoutError.

To avoid the task cancellation,wrap it in shield().

The function will wait until the future is actually cancelled,so the total wait time may exceed the timeout. If an exceptionhappens during cancellation, it is propagated.

If the wait is cancelled, the future aw is also cancelled.

Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.

Example:

Changed in version 3.7: When aw is cancelled due to a timeout, wait_for waitsfor aw to be cancelled. Previously, it raisedasyncio.TimeoutError immediately.

coroutine asyncio.wait(aws, *, loop=None, timeout=None, return_when=ALL_COMPLETED)

Run awaitable objects in the awsset concurrently and block until the condition specifiedby return_when.

The aws set must not be empty.

Returns two sets of Tasks/Futures: (done,pending).

Usage:

timeout (a float or int), if specified, can be used to controlthe maximum number of seconds to wait before returning.

Note that this function does not raise asyncio.TimeoutError.Futures or Tasks that aren’t done when the timeout occurs are simplyreturned in the second set.

return_when indicates when this function should return. It mustbe one of the following constants:

Constant

Description

FIRST_COMPLETED

The function will return when anyfuture finishes or is cancelled.

FIRST_EXCEPTION

The function will return when anyfuture finishes by raising anexception. If no future raises anexception then it is equivalent toALL_COMPLETED.

ALL_COMPLETED

The function will return when allfutures finish or are cancelled.

Unlike wait_for(), wait() does not cancel thefutures when a timeout occurs.

Deprecated since version 3.8: If any awaitable in aws is a coroutine, it is automaticallyscheduled as a Task. Passing coroutines objects towait() directly is deprecated as it leads toconfusing behavior.

Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.

Note

wait() schedules coroutines as Tasks automatically and laterreturns those implicitly created Task objects in (done,pending)sets. Therefore the following code won’t work as expected:

Here is how the above snippet can be fixed:

Deprecated since version 3.8, will be removed in version 3.11: Passing coroutine objects to wait() directly isdeprecated.

asyncio.as_completed(aws, *, loop=None, timeout=None)

Run awaitable objects in the awsset concurrently. Return an iterator of coroutines.Each coroutine returned can be awaited to get the earliest nextresult from the set of the remaining awaitables.

Raises asyncio.TimeoutError if the timeout occurs beforeall Futures are done.

Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.

Example:

coroutine asyncio.to_thread(func, /, *args, **kwargs)

Asynchronously run function func in a separate thread.

Any *args and **kwargs supplied for this function are directly passedto func. Also, the current contextvars.Context is propogated,allowing context variables from the event loop thread to be accessed in theseparate thread.

Return a coroutine that can be awaited to get the eventual result of func.

This coroutine function is primarily intended to be used for executingIO-bound functions/methods that would otherwise block the event loop ifthey were ran in the main thread. For example:

Directly calling blocking_io() in any coroutine would block the event loopfor its duration, resulting in an additional 1 second of run time. Instead,by using asyncio.to_thread(), we can run it in a separate thread withoutblocking the event loop.

Note

Due to the GIL, asyncio.to_thread() can typically only be usedto make IO-bound functions non-blocking. However, for extension modulesthat release the GIL or alternative Python implementations that don’thave one, asyncio.to_thread() can also be used for CPU-bound functions.

asyncio.run_coroutine_threadsafe(coro, loop)

Submit a coroutine to the given event loop. Thread-safe.

Return a concurrent.futures.Future to wait for the resultfrom another OS thread.

This function is meant to be called from a different OS threadthan the one where the event loop is running. Example:

If an exception is raised in the coroutine, the returned Futurewill be notified. It can also be used to cancel the task inthe event loop:

See the concurrency and multithreadingsection of the documentation.

Unlike other asyncio functions this function requires the loopargument to be passed explicitly.

New in version 3.5.1.

asyncio.current_task(loop=None)

Return the currently running Task instance, or None ifno task is running.

If loop is Noneget_running_loop() is used to getthe current loop.

asyncio.all_tasks(loop=None)

Return a set of not yet finished Task objects run bythe loop.

If loop is None, get_running_loop() is used for gettingcurrent loop.

New in version 3.7.

class asyncio.Task(coro, *, loop=None, name=None)

A Future-like object that runs a Pythoncoroutine. Not thread-safe.

Tasks are used to run coroutines in event loops.If a coroutine awaits on a Future, the Task suspendsthe execution of the coroutine and waits for the completionof the Future. When the Future is done, the execution ofthe wrapped coroutine resumes.

Event loops use cooperative scheduling: an event loop runsone Task at a time. While a Task awaits for the completion of aFuture, the event loop runs other Tasks, callbacks, or performsIO operations.

Use the high-level asyncio.create_task() function to createTasks, or the low-level loop.create_task() orensure_future() functions. Manual instantiation of Tasksis discouraged.

To cancel a running Task use the cancel() method. Calling itwill cause the Task to throw a CancelledError exception intothe wrapped coroutine. If a coroutine is awaiting on a Futureobject during cancellation, the Future object will be cancelled.

cancelled() can be used to check if the Task was cancelled.The method returns True if the wrapped coroutine did notsuppress the CancelledError exception and was actuallycancelled.

asyncio.Task inherits from Future all of itsAPIs except Future.set_result() andFuture.set_exception().

Tasks support the contextvars module. When a Taskis created it copies the current context and later runs itscoroutine in the copied context.

Changed in version 3.7: Added support for the contextvars module.

Tasks 1 0 3 fraction

Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.

cancel(msg=None)

Request the Task to be cancelled.

This arranges for a CancelledError exception to be throwninto the wrapped coroutine on the next cycle of the event loop.

The coroutine then has a chance to clean up or even deny therequest by suppressing the exception with a try …… exceptCancelledErrorfinally block.Therefore, unlike Future.cancel(), Task.cancel() doesnot guarantee that the Task will be cancelled, althoughsuppressing cancellation completely is not common and is activelydiscouraged.

Tasks 1 0 3 Sezonas

The following example illustrates how coroutines can interceptthe cancellation request:

cancelled()

Return True if the Task is cancelled.

The Task is cancelled when the cancellation was requested withcancel() and the wrapped coroutine propagated theCancelledError exception thrown into it.

done()

Return True if the Task is done.

A Task is done when the wrapped coroutine either returneda value, raised an exception, or the Task was cancelled.

result()

Return the result of the Task.

If the Task is done, the result of the wrapped coroutineis returned (or if the coroutine raised an exception, thatexception is re-raised.)

If the Task has been cancelled, this method raisesa CancelledError exception.

If the Task’s result isn’t yet available, this method raisesa InvalidStateError exception.

exception()

Return the exception of the Task.

If the wrapped coroutine raised an exception that exceptionis returned. If the wrapped coroutine returned normallythis method returns None.

If the Task has been cancelled, this method raises aCancelledError exception.

If the Task isn’t done yet, this method raises anInvalidStateError exception.

add_done_callback(callback, *, context=None)

Add a callback to be run when the Task is done.

This method should only be used in low-level callback-based code.

See the documentation of Future.add_done_callback()for more details.

remove_done_callback(callback)

Remove callback from the callbacks list.

This method should only be used in low-level callback-based code.

See the documentation of Future.remove_done_callback()for more details.

get_stack(*, limit=None)

Return the list of stack frames for this Task.

If the wrapped coroutine is not done, this returns the stackwhere it is suspended. If the coroutine has completedsuccessfully or was cancelled, this returns an empty list.If the coroutine was terminated by an exception, this returnsthe list of traceback frames.

The frames are always ordered from oldest to newest.

Only one stack frame is returned for a suspended coroutine.

The optional limit argument sets the maximum number of framesto return; by default all available frames are returned.The ordering of the returned list differs depending on whethera stack or a traceback is returned: the newest frames of astack are returned, but the oldest frames of a traceback arereturned. (This matches the behavior of the traceback module.)

print_stack(*, limit=None, file=None)

Print the stack or traceback for this Task.

This produces output similar to that of the traceback modulefor the frames retrieved by get_stack().

The limit argument is passed to get_stack() directly.

The file argument is an I/O stream to which the outputis written; by default output is written to sys.stderr.

get_coro()

Return the coroutine object wrapped by the Task.

New in version 3.8.

get_name()

Return the name of the Task.

If no name has been explicitly assigned to the Task, the defaultasyncio Task implementation generates a default name duringinstantiation.

set_name(value)

Set the name of the Task.

The value argument can be any object, which is thenconverted to a string.

In the default Task implementation, the name will be visiblein the repr() output of a task object.

New in version 3.8.

Note

Support for generator-based coroutines is deprecated andis scheduled for removal in Python 3.10.

Generator-based coroutines predate async/await syntax. They arePython generators that use yieldfrom expressions to awaiton Futures and other coroutines.

Generator-based coroutines should be decorated with@asyncio.coroutine, although this is notenforced.

@asyncio.coroutine

Decorator to mark generator-based coroutines.

This decorator enables legacy generator-based coroutines to becompatible with async/await code:

This decorator should not be used for asyncdefcoroutines.

Deprecated since version 3.8, will be removed in version 3.10: Use asyncdef instead.

asyncio.iscoroutine(obj)

Return True if obj is a coroutine object.

This method is different from inspect.iscoroutine() becauseit returns True for generator-based coroutines.

asyncio.iscoroutinefunction(func)

Return True if func is a coroutine function.

This method is different from inspect.iscoroutinefunction()because it returns True for generator-based coroutine functionsdecorated with @coroutine.