Debian Codegraph @

docs/source/tutorial.rst

raw
1 Tutorial
2 ========
3
4 .. The Trio tutorial
5
6 the spiel about what a concurrent library is
7
8 Traditionally Python is a synchronous language, and we assume
9 you're familiar with that kind of programming, but don't assume any
10 knowledge of concurrent programming. (And even if you are familiar
11 with concurrent programming using another library like Twisted or
12 asyncio, or another language like Go or Erlang, then you should
13 still probably read this, because Trio is different.)
14
15 Trio turns Python into a concurrent language. It takes the core
16 async/await syntax introduced in 3.5, and uses it to add two
17 new pieces of semantics:
18
19 - cancel scopes: a generic system for managing timeouts and
20 cancellation
21 - nurseries: which let your program do multiple things at the same
22 time
23
24 Of course it also provides a complete suite of APIs for doing
25 networking, file I/O, using worker threads,
26
27 We'll go through and explain each of these
28
29 simple cancellation
30 applied to an HTTP request
31 with fail_after(5):
32 response = await asks.get("https://httpbin.org/delay/1")
33 print(response)
34 and then again with /delay/10
35
36 value of async/await: show you where the cancellation exceptions
37 can happen -- see pillar re: explicit cancel points
38
39 (also briefly discuss cancel scopes and cancel() + the query APIs,
40 fail_after vs move_on_after, current_time() and
41 current_effective_deadline())
42
43 simple multi-task concurrency
44 applied to do multiple HTTP requests
45 adding a per-request timeout
46 adding a timeout on the whole thing -- demonstrating wrapping
47 cancel around a nursery
48
49 pillars: implicit concurrency and exception raising
50 and explicit schedule points
51
52 example: the scheduling trace
53
54 implicit concurrency -> use echo example to introduce networking
55 API, and show how to do explicit concurrency
56 and demonstrate start()
57 then point out that you can just use serve_tcp()
58
59 example: catch-all logging in our echo server
60
61 review of the three (or four) core language extensions
62 and how they fit together and
63
64 .. currentmodule:: trio
65
66 Welcome to the Trio tutorial! Trio is a modern Python library for
67 writing asynchronous applications – that is, programs that want to do
68 multiple things at the same time with parallelized I/O, like a web
69 spider that fetches lots of pages in parallel, a web server juggling
70 lots of simultaneous downloads... that sort of thing. Here we'll try
71 to give a gentle introduction to asynchronous programming with Trio.
72
73 We assume that you're familiar with Python in general, but don't worry
74 – we don't assume you know anything about asynchronous programming or
75 Python's new ``async/await`` feature.
76
77 Also, unlike many ``async/await`` tutorials, we assume that your goal
78 is to *use* Trio to write interesting programs, so we won't go into
79 the nitty-gritty details of how ``async/await`` is implemented inside
80 the Python interpreter. The word "coroutine" is never mentioned. The
81 fact is, you really don't *need* to know any of that stuff unless you
82 want to *implement* a library like Trio, so we leave it out (though
83 we'll throw in a few links for those who want to dig deeper).
84
85 Okay, ready? Let's get started.
86
87
88 Before you begin
89 ----------------
90
91 1. Make sure you're using Python 3.10 or newer.
92
93 2. ``python3 -m pip install --upgrade trio`` (or on Windows, maybe
94 ``py -3 -m pip install --upgrade trio`` – `details
95 <https://packaging.python.org/installing/>`__)
96
97 3. Can you ``import trio``? If so then you're good to go!
98
99
100 If you get lost or confused...
101 ------------------------------
102
103 ...then we want to know! We have a friendly `chat channel
104 <https://gitter.im/python-trio/general>`__, you can ask questions
105 `using the "python-trio" tag on StackOverflow
106 <https://stackoverflow.com/questions/ask?tags=python+python-trio>`__, or just
107 `file a bug <https://github.com/python-trio/trio/issues/new>`__ (if
108 our documentation is confusing, that's our fault, and we want to fix
109 it!).
110
111
112 Async functions
113 ---------------
114
115 Python 3.5 added a major new feature: async functions. Using Trio is
116 all about writing async functions, so let's start there.
117
118 An async function is defined like a normal function, except you write
119 ``async def`` instead of ``def``:
120
121 .. code-block:: python
122
123 # A regular function
124 def regular_double(x):
125 return 2 * x
126
127 # An async function
128 async def async_double(x):
129 return 2 * x
130
131 "Async" is short for "asynchronous"; we'll sometimes refer to regular
132 functions like ``regular_double`` as "synchronous functions", to
133 distinguish them from async functions.
134
135 From a user's point of view, there are two differences between an
136 async function and a regular function:
137
138 1. To call an async function, you have to use the ``await``
139 keyword. So instead of writing ``regular_double(3)``, you write
140 ``await async_double(3)``.
141
142 2. You can't use the ``await`` keyword inside the body of a regular
143 function. If you try it, you'll get a syntax error:
144
145 .. code-block:: python
146
147 def print_double(x):
148 print(await async_double(x)) # <-- SyntaxError here
149
150 But inside an async function, ``await`` is allowed:
151
152 .. code-block:: python
153
154 async def print_double(x):
155 print(await async_double(x)) # <-- OK!
156
157 Now, let's think about the consequences here: if you need ``await`` to
158 call an async function, and only async functions can use
159 ``await``... here's a little table:
160
161 ======================= ================================== ===================
162 If a function like this wants to call a function like this is it gonna happen?
163 ======================= ================================== ===================
164 sync sync ✓
165 sync async **NOPE**
166 async sync ✓
167 async async ✓
168 ======================= ================================== ===================
169
170 So in summary: As a user, the entire advantage of async functions over
171 regular functions is that async functions have a superpower: they can
172 call other async functions.
173
174 This immediately raises two questions: how, and why? Specifically:
175
176 When your Python program starts up, it's running regular old sync
177 code. So there's a chicken-and-the-egg problem: once we're running an
178 async function we can call other async functions, but *how* do we call
179 that first async function?
180
181 And, if the only reason to write an async function is that it can call
182 other async functions, *why* on earth would we ever use them in
183 the first place? I mean, as superpowers go this seems a bit
184 pointless. Wouldn't it be simpler to just... not use any async
185 functions at all?
186
187 This is where an async library like Trio comes in. It provides two
188 things:
189
190 1. A runner function, which is a special *synchronous* function that
191 takes and calls an *asynchronous* function. In Trio, this is
192 ``trio.run``:
193
194 .. code-block:: python
195
196 import trio
197
198 async def async_double(x):
199 return 2 * x
200
201 trio.run(async_double, 3) # returns 6
202
203 So that answers the "how" part.
204
205 2. A bunch of useful async functions – in particular, functions for
206 doing I/O. So that answers the "why": these functions are async,
207 and they're useful, so if you want to use them, you have to write
208 async code. If you think keeping track of these ``async`` and
209 ``await`` things is annoying, then too bad – you've got no choice
210 in the matter! (Well, OK, you could just not use Trio. That's a
211 legitimate option. But it turns out that the ``async/await`` stuff
212 is actually a good thing, for reasons we'll discuss a little bit
213 later.)
214
215 Here's an example function that uses
216 :func:`trio.sleep`. (:func:`trio.sleep` is like :func:`time.sleep`,
217 but with more async.)
218
219 .. code-block:: python
220
221 import trio
222
223 async def double_sleep(x):
224 await trio.sleep(2 * x)
225
226 trio.run(double_sleep, 3) # does nothing for 6 seconds then returns
227
228 .. _async-sandwich:
229
230 So it turns out our ``async_double`` function is actually a bad
231 example. I mean, it works, it's fine, there's nothing *wrong* with it,
232 but it's pointless: it could just as easily be written as a regular
233 function, and it would be more useful that way. ``double_sleep`` is a
234 much more typical example: we have to make it async, because it calls
235 another async function. The end result is a kind of async sandwich,
236 with Trio on both sides and our code in the middle:
237
238 .. code-block:: none
239
240 trio.run -> double_sleep -> trio.sleep
241
242 This "sandwich" structure is typical for async code; in general, it
243 looks like:
244
245 .. code-block:: none
246
247 trio.run -> [async function] -> ... -> [async function] -> trio.whatever
248
249 It's exactly the functions on the path between :func:`trio.run` and
250 ``trio.whatever`` that have to be async. Trio provides the async
251 bread, and then your code makes up the async sandwich's tasty async
252 filling. Other functions (e.g., helpers you call along the way) should
253 generally be regular, non-async functions.
254
255
256 Warning: don't forget that ``await``!
257 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
258
259 Now would be a good time to open up a Python prompt and experiment a
260 little with writing simple async functions and running them with
261 ``trio.run``.
262
263 At some point in this process, you'll probably write some code like
264 this, that tries to call an async function but leaves out the
265 ``await``:
266
267 .. code-block:: python
268
269 import time
270 import trio
271
272 async def broken_double_sleep(x):
273 print("*yawn* Going to sleep")
274 start_time = time.perf_counter()
275
276 # Whoops, we forgot the 'await'!
277 trio.sleep(2 * x)
278
279 sleep_time = time.perf_counter() - start_time
280 print(f"Woke up after {sleep_time:.2f} seconds, feeling well rested!")
281
282 trio.run(broken_double_sleep, 3)
283
284 You might think that Python would raise an error here, like it does
285 for other kinds of mistakes we sometimes make when calling a
286 function. Like, if we forgot to pass :func:`trio.sleep` its required
287 argument, then we would get a nice :exc:`TypeError` saying so. But
288 unfortunately, if you forget an ``await``, you don't get that. What
289 you actually get is:
290
291 .. code-block:: pycon
292
293 >>> trio.run(broken_double_sleep, 3)
294 *yawn* Going to sleep
295 Woke up after 0.00 seconds, feeling well rested!
296 __main__:4: RuntimeWarning: coroutine 'sleep' was never awaited
297 >>>
298
299 This is clearly broken – 0.00 seconds is not long enough to feel well
300 rested! Yet the code acts like it succeeded – no exception was
301 raised. The only clue that something went wrong is that it prints
302 ``RuntimeWarning: coroutine 'sleep' was never awaited``. Also, the
303 exact place where the warning is printed might vary, because it
304 depends on the whims of the garbage collector. If you're using PyPy,
305 you might not even get a warning at all until the next GC collection
306 runs:
307
308 .. code-block:: pycon
309
310 # On PyPy:
311 >>> trio.run(broken_double_sleep, 3)
312 *yawn* Going to sleep
313 Woke up after 0.00 seconds, feeling well rested!
314 >>> # what the ... ?? not even a warning!
315
316 >>> # but forcing a garbage collection gives us a warning:
317 >>> import gc
318 >>> gc.collect()
319 /home/njs/pypy-3.8-nightly/lib-python/3/importlib/_bootstrap.py:191: RuntimeWarning: coroutine 'sleep' was never awaited
320 if _module_locks.get(name) is wr: # XXX PyPy fix?
321 0
322
323 (If you can't see the warning above, try scrolling right.)
324
325 Forgetting an ``await`` like this is an *incredibly common
326 mistake*. You will mess this up. Everyone does. And Python will not
327 help you as much as you'd hope 😞. The key thing to remember is: if
328 you see the magic words ``RuntimeWarning: coroutine '...' was never
329 awaited``, then this *always* means that you made the mistake of
330 leaving out an ``await`` somewhere, and you should ignore all the
331 other error messages you see and go fix that first, because there's a
332 good chance the other stuff is just collateral damage. I'm not even
333 sure what all that other junk in the PyPy output is. Fortunately I
334 don't need to know, I just need to fix my function!
335
336 ("I thought you said you weren't going to mention coroutines!" Yes,
337 well, *I* didn't mention coroutines, Python did. Take it up with
338 Guido! But seriously, this is unfortunately a place where the internal
339 implementation details do leak out a bit.)
340
341 Why does this happen? In Trio, every time we use ``await`` it's to
342 call an async function, and every time we call an async function we
343 use ``await``. But Python's trying to keep its options open for other
344 libraries that are *ahem* a little less organized about things. So
345 while for our purposes we can think of ``await trio.sleep(...)`` as a
346 single piece of syntax, Python thinks of it as two things: first a
347 function call that returns this weird "coroutine" object:
348
349 .. code-block:: pycon
350
351 >>> trio.sleep(3)
352 <coroutine object sleep at 0x7f5ac77be6d0>
353
354 and then that object gets passed to ``await``, which actually runs the
355 function. So if you forget ``await``, then two bad things happen: your
356 function doesn't actually get called, and you get a "coroutine" object
357 where you might have been expecting something else, like a number:
358
359 .. code-block:: pycon
360
361 >>> async_double(3) + 1
362 TypeError: unsupported operand type(s) for +: 'coroutine' and 'int'
363
364 If you didn't already mess this up naturally, then give it a try on
365 purpose: try writing some code with a missing ``await``, or an extra
366 ``await``, and see what you get. This way you'll be prepared for when
367 it happens to you for real.
368
369 And remember: watch out for ``RuntimeWarning: coroutine '...' was
370 never awaited``; it means you need to find and fix your missing
371 ``await``.
372
373
374 Okay, let's see something cool already
375 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
376
377 So now we've started using Trio, but so far all we've learned to do is
378 write functions that print things and sleep for various lengths of
379 time. Interesting enough, but we could just as easily have done that
380 with :func:`time.sleep`. ``async/await`` is useless!
381
382 Well, not really. Trio has one more trick up its sleeve, that makes
383 async functions more powerful than regular functions: it can run
384 multiple async functions *at the same time*. Here's an example:
385
386 .. _tutorial-example-tasks-intro:
387
388 .. literalinclude:: tutorial/tasks-intro.py
389 :linenos:
390
391 There's a lot going on in here, so we'll take it one step at a
392 time. In the first part, we define two async functions ``child1`` and
393 ``child2``. These should look familiar from the last section:
394
395 .. literalinclude:: tutorial/tasks-intro.py
396 :linenos:
397 :lineno-match:
398 :start-at: async def child1
399 :end-at: child2: exiting
400
401 Next, we define ``parent`` as an async function that's going to call
402 ``child1`` and ``child2`` concurrently:
403
404 .. literalinclude:: tutorial/tasks-intro.py
405 :linenos:
406 :lineno-match:
407 :start-at: async def parent
408 :end-at: all done!
409
410 It does this by using a mysterious ``async with`` statement to create
411 a "nursery", and then "spawns" ``child1`` and ``child2`` into the
412 nursery.
413
414 Let's start with this ``async with`` thing. It's actually pretty
415 simple. In regular Python, a statement like ``with someobj: ...``
416 instructs the interpreter to call ``someobj.__enter__()`` at the
417 beginning of the block, and to call ``someobj.__exit__()`` at the end
418 of the block. We call ``someobj`` a "context manager". An ``async
419 with`` does exactly the same thing, except that where a regular
420 ``with`` statement calls regular methods, an ``async with`` statement
421 calls async methods: at the start of the block it does ``await
422 someobj.__aenter__()`` and at that end of the block it does ``await
423 someobj.__aexit__()``. In this case we call ``someobj`` an "async
424 context manager". So in short: ``with`` blocks are a shorthand for
425 calling some functions, and since with async/await Python now has two
426 kinds of functions, it also needs two kinds of ``with`` blocks. That's
427 all there is to it! If you understand async functions, then you
428 understand ``async with``.
429
430 .. note::
431
432 This example doesn't use them, but while we're here we might as
433 well mention the one other piece of new syntax that async/await
434 added: ``async for``. It's basically the same idea as ``async
435 with`` versus ``with``: An ``async for`` loop is just like a
436 ``for`` loop, except that where a ``for`` loop does
437 ``iterator.__next__()`` to fetch the next item, an ``async for``
438 does ``await async_iterator.__anext__()``. Now you understand all
439 of async/await. Basically just remember that it involves making
440 sandwiches and sticking the word "async" in front of everything,
441 and you'll do fine.
442
443 Now that we understand ``async with``, let's look at ``parent`` again:
444
445 .. literalinclude:: tutorial/tasks-intro.py
446 :linenos:
447 :lineno-match:
448 :start-at: async def parent
449 :end-at: all done!
450
451 There are only 4 lines of code that really do anything here. On line
452 20, we use :func:`trio.open_nursery` to get a "nursery" object, and
453 then inside the ``async with`` block we call ``nursery.start_soon`` twice,
454 on lines 22 and 25. There are actually two ways to call an async
455 function: the first one is the one we already saw, using ``await
456 async_fn()``; the new one is ``nursery.start_soon(async_fn)``: it asks Trio
457 to start running this async function, *but then returns immediately
458 without waiting for the function to finish*. So after our two calls to
459 ``nursery.start_soon``, ``child1`` and ``child2`` are now running in the
460 background. And then at line 28, the commented line, we hit the end of
461 the ``async with`` block, and the nursery's ``__aexit__`` function
462 runs. What this does is force ``parent`` to stop here and wait for all
463 the children in the nursery to exit. This is why you have to use
464 ``async with`` to get a nursery: it gives us a way to make sure that
465 the child calls can't run away and get lost. One reason this is
466 important is that if there's a bug or other problem in one of the
467 children, and it raises an exception, then it lets us propagate that
468 exception into the parent; in many other frameworks, exceptions like
469 this are just discarded. Trio never discards exceptions.
470
471 Ok! Let's try running it and see what we get:
472
473 .. code-block:: none
474
475 parent: started!
476 parent: spawning child1...
477 parent: spawning child2...
478 parent: waiting for children to finish...
479 child2: started! sleeping now...
480 child1: started! sleeping now...
481 [... 1 second passes ...]
482 child1: exiting!
483 child2: exiting!
484 parent: all done!
485
486 (Your output might have the order of the "started" and/or "exiting"
487 lines swapped compared to mine.)
488
489 Notice that ``child1`` and ``child2`` both start together and then
490 both exit together. And, even though we made two calls to
491 ``trio.sleep(1)``, the program finished in just one second total.
492 So it looks like ``child1`` and ``child2`` really are running at the
493 same time!
494
495 Now, if you're familiar with programming using threads, this might
496 look familiar – and that's intentional. But it's important to realize
497 that *there are no threads here*. All of this is happening in a single
498 thread. To remind ourselves of this, we use slightly different
499 terminology: instead of spawning two "threads", we say that we spawned
500 two "tasks". There are two differences between tasks and threads: (1)
501 many tasks can take turns running on a single thread, and (2) with
502 threads, the Python interpreter/operating system can switch which
503 thread is running whenever they feel like it; with tasks, we can only
504 switch at certain designated places we call :ref:`"checkpoints"
505 <checkpoints>`. In the next section, we'll dig into what this means.
506
507
508 .. _tutorial-instrument-example:
509
510 Task switching illustrated
511 ~~~~~~~~~~~~~~~~~~~~~~~~~~
512
513 The big idea behind async/await-based libraries like Trio is to run
514 lots of tasks simultaneously on a single thread by switching between
515 them at appropriate places – so for example, if we're implementing a
516 web server, then one task could be sending an HTTP response at the
517 same time as another task is waiting for new connections. If all you
518 want to do is use Trio, then you don't need to understand all the
519 nitty-gritty detail of how this switching works – but it's very useful
520 to have at least a general intuition about what Trio is doing "under
521 the hood" when your code is executing. To help build that intuition,
522 let's look more closely at how Trio ran our example from the last
523 section.
524
525 Fortunately, Trio provides a :ref:`rich set of tools for inspecting
526 and debugging your programs <instrumentation>`. Here we want to watch
527 :func:`trio.run` at work, which we can do by writing a class we'll
528 call ``Tracer``, which implements Trio's :class:`~trio.abc.Instrument`
529 interface. Its job is to log various events as they happen:
530
531 .. literalinclude:: tutorial/tasks-with-trace.py
532 :pyobject: Tracer
533
534 Then we re-run our example program from the previous section, but this
535 time we pass :func:`trio.run` a ``Tracer`` object:
536
537 .. literalinclude:: tutorial/tasks-with-trace.py
538 :start-at: trio.run
539
540 This generates a *lot* of output, so we'll go through it one step at a
541 time.
542
543 First, there's a bit of chatter while Trio gets ready to run our
544 code. Most of this is irrelevant to us for now, but in the middle you
545 can see that Trio has created a task for the ``__main__.parent``
546 function, and "scheduled" it (i.e., made a note that it should be run
547 soon):
548
549 .. code-block:: none
550
551 $ python3 tutorial/tasks-with-trace.py
552 !!! run started
553 ### new task spawned: <init>
554 ### task scheduled: <init>
555 ### doing a quick check for I/O
556 ### finished I/O check (took 1.1122087016701698e-05 seconds)
557 >>> about to run one step of task: <init>
558 ### new task spawned: <call soon task>
559 ### task scheduled: <call soon task>
560 ### new task spawned: __main__.parent
561 ### task scheduled: __main__.parent
562 <<< task step finished: <init>
563 ### doing a quick check for I/O
564 ### finished I/O check (took 6.4980704337358475e-06 seconds)
565
566 Once the initial housekeeping is done, Trio starts running the
567 ``parent`` function, and you can see ``parent`` creating the two child
568 tasks. Then it hits the end of the ``async with`` block, and pauses:
569
570 .. code-block:: none
571
572 >>> about to run one step of task: __main__.parent
573 parent: started!
574 parent: spawning child1...
575 ### new task spawned: __main__.child1
576 ### task scheduled: __main__.child1
577 parent: spawning child2...
578 ### new task spawned: __main__.child2
579 ### task scheduled: __main__.child2
580 parent: waiting for children to finish...
581 <<< task step finished: __main__.parent
582
583 Control then goes back to :func:`trio.run`, which logs a bit more
584 internal chatter:
585
586 .. code-block:: none
587
588 >>> about to run one step of task: <call soon task>
589 <<< task step finished: <call soon task>
590 ### doing a quick check for I/O
591 ### finished I/O check (took 5.476875230669975e-06 seconds)
592
593 And then gives the two child tasks a chance to run:
594
595 .. code-block:: none
596
597 >>> about to run one step of task: __main__.child2
598 child2 started! sleeping now...
599 <<< task step finished: __main__.child2
600
601 >>> about to run one step of task: __main__.child1
602 child1: started! sleeping now...
603 <<< task step finished: __main__.child1
604
605 Each task runs until it hits the call to :func:`trio.sleep`, and then
606 suddenly we're back in :func:`trio.run` deciding what to run next. How
607 does this happen? The secret is that :func:`trio.run` and
608 :func:`trio.sleep` work together to make it happen: :func:`trio.sleep`
609 has access to some special magic that lets it pause itself,
610 so it sends a note to :func:`trio.run` requesting to be
611 woken again after 1 second, and then suspends the task. And once the
612 task is suspended, Python gives control back to :func:`trio.run`,
613 which decides what to do next. (If this sounds similar to the way that
614 generators can suspend execution by doing a ``yield``, then that's not
615 a coincidence: inside the Python interpreter, there's a lot of overlap
616 between the implementation of generators and async functions.)
617
618 .. note::
619
620 You might wonder whether you can mix-and-match primitives from
621 different async libraries. For example, could we use
622 :func:`trio.run` together with :func:`asyncio.sleep`? The answer is
623 no, we can't, and the paragraph above explains why: the two sides
624 of our async sandwich have a private language they use to talk to
625 each other, and different libraries use different languages. So if
626 you try to call :func:`asyncio.sleep` from inside a
627 :func:`trio.run`, then Trio will get very confused indeed and
628 probably blow up in some dramatic way.
629
630 Only async functions have access to the special magic for suspending a
631 task, so only async functions can cause the program to switch to a
632 different task. What this means is that if a call *doesn't* have an ``await``
633 on it, then you know that it *can't* be a place where your task will
634 be suspended. This makes tasks much `easier to reason about
635 <https://glyph.twistedmatrix.com/2014/02/unyielding.html>`__ than
636 threads, because there are far fewer ways that tasks can be
637 interleaved with each other and stomp on each others' state. (For
638 example, in Trio a statement like ``a += 1`` is always atomic – even
639 if ``a`` is some arbitrarily complicated custom object!) Trio also
640 makes some :ref:`further guarantees beyond that <checkpoints>`, but
641 that's the big one.
642
643 And now you also know why ``parent`` had to use an ``async with`` to
644 open the nursery: if we had used a regular ``with`` block, then it
645 wouldn't have been able to pause at the end and wait for the children
646 to finish; we need our cleanup function to be async, which is exactly
647 what ``async with`` gives us.
648
649 Now, back to our execution point. To recap: at this point ``parent``
650 is waiting on ``child1`` and ``child2``, and both children are
651 sleeping. So :func:`trio.run` checks its notes, and sees that there's
652 nothing to be done until those sleeps finish – unless possibly some
653 external I/O event comes in. If that happened, then it might give us
654 something to do. Of course we aren't doing any I/O here so it won't
655 happen, but in other situations it could. So next it calls an
656 operating system primitive to put the whole process to sleep:
657
658 .. code-block:: none
659
660 ### waiting for I/O for up to 0.9999009938910604 seconds
661
662 And in fact no I/O does arrive, so one second later we wake up again,
663 and Trio checks its notes again. At this point it checks the current
664 time, compares it to the notes that :func:`trio.sleep` sent saying
665 when the two child tasks should be woken up again, and realizes
666 that they've slept for long enough, so it schedules them to run soon:
667
668 .. code-block:: none
669
670 ### finished I/O check (took 1.0006483688484877 seconds)
671 ### task scheduled: __main__.child1
672 ### task scheduled: __main__.child2
673
674 And then the children get to run, and this time they run to
675 completion. Remember how ``parent`` is waiting for them to finish?
676 Notice how ``parent`` gets scheduled when the first child exits:
677
678 .. code-block:: none
679
680 >>> about to run one step of task: __main__.child1
681 child1: exiting!
682 ### task scheduled: __main__.parent
683 ### task exited: __main__.child1
684 <<< task step finished: __main__.child1
685
686 >>> about to run one step of task: __main__.child2
687 child2 exiting!
688 ### task exited: __main__.child2
689 <<< task step finished: __main__.child2
690
691 Then, after another check for I/O, ``parent`` wakes up. The nursery
692 cleanup code notices that all its children have exited, and lets the
693 nursery block finish. And then ``parent`` makes a final print and
694 exits:
695
696 .. code-block:: none
697
698 ### doing a quick check for I/O
699 ### finished I/O check (took 9.045004844665527e-06 seconds)
700
701 >>> about to run one step of task: __main__.parent
702 parent: all done!
703 ### task scheduled: <init>
704 ### task exited: __main__.parent
705 <<< task step finished: __main__.parent
706
707 And finally, after a bit more internal bookkeeping, :func:`trio.run`
708 exits too:
709
710 .. code-block:: none
711
712 ### doing a quick check for I/O
713 ### finished I/O check (took 5.996786057949066e-06 seconds)
714 >>> about to run one step of task: <init>
715 ### task scheduled: <call soon task>
716 ### task scheduled: <init>
717 <<< task step finished: <init>
718 ### doing a quick check for I/O
719 ### finished I/O check (took 6.258022040128708e-06 seconds)
720 >>> about to run one step of task: <call soon task>
721 ### task exited: <call soon task>
722 <<< task step finished: <call soon task>
723 >>> about to run one step of task: <init>
724 ### task exited: <init>
725 <<< task step finished: <init>
726 !!! run finished
727
728 You made it!
729
730 That was a lot of text, but again, you don't need to understand
731 everything here to use Trio – in fact, Trio goes to great lengths to
732 make each task feel like it executes in a simple, linear way. (Just
733 like your operating system goes to great lengths to make it feel like
734 your single-threaded code executes in a simple linear way, even though
735 under the covers the operating system juggles between different
736 threads and processes in essentially the same way Trio does.) But it
737 is useful to have a rough model in your head of how the code you write
738 is actually executed, and – most importantly – the consequences of
739 that for parallelism.
740
741 Alternatively, if this has just whetted your appetite and you want to
742 know more about how ``async/await`` works internally, then `this blog
743 post
744 <https://snarky.ca/how-the-heck-does-async-await-work-in-python-3-5/>`__
745 is a good deep dive, or check out `this great walkthrough
746 <https://github.com/AndreLouisCaron/a-tale-of-event-loops>`__ to see
747 how to build a simple async I/O framework from the ground up.
748
749
750 A kinder, gentler GIL
751 ---------------------
752
753 Speaking of parallelism – let's zoom out for a moment and talk about
754 how async/await compares to other ways of handling concurrency in
755 Python.
756
757 As we've already noted, Trio tasks are conceptually rather similar to
758 Python's built-in threads, as provided by the :mod:`threading`
759 module. And in all common Python implementations, threads have a
760 famous limitation: the Global Interpreter Lock, or "GIL" for
761 short. The GIL means that even if you use multiple threads, your code
762 still (mostly) ends up running on a single core. People tend to find
763 this frustrating.
764
765 But from Trio's point of view, the problem with the GIL isn't that it
766 restricts parallelism. Of course it would be nice if Python had better
767 options for taking advantage of multiple cores, but that's an
768 extremely difficult problem to solve, and in the meantime there are
769 lots of problems where a single core is totally adequate – or where if
770 it isn't, then process-level or machine-level parallelism works fine.
771
772 No, the problem with the GIL is that it's a *lousy deal*: we give up
773 on using multiple cores, and in exchange we get... almost all the same
774 challenges and mind-bending bugs that come with real parallel
775 programming, and – to add insult to injury – `pretty poor scalability
776 <https://twitter.com/hynek/status/771790449057132544>`__. Threads in
777 Python just aren't that appealing.
778
779 Trio doesn't make your code run on multiple cores; in fact, as we saw
780 above, it's baked into Trio's design that when it has multiple tasks,
781 they take turns, so at each moment only one of them is actively running.
782 We're not so much overcoming the GIL as embracing it. But if you're
783 willing to accept that, plus a bit of extra work to put these new
784 ``async`` and ``await`` keywords in the right places, then in exchange
785 you get:
786
787 * Excellent scalability: Trio can run 10,000+ tasks simultaneously
788 without breaking a sweat, so long as their total CPU demands don't
789 exceed what a single core can provide. (This is common in, for
790 example, network servers that have lots of clients connected, but
791 only a few active at any given time.)
792
793 * Fancy features: most threading systems are implemented in C and
794 restricted to whatever features the operating system provides. In
795 Trio our logic is all in Python, which makes it possible to
796 implement powerful and ergonomic features like :ref:`Trio's
797 cancellation system <cancellation>`.
798
799 * Code that's easier to reason about: the ``await`` keyword means that
800 potential task-switching points are explicitly marked within each
801 function. This can make Trio code `dramatically easier to reason
802 about <https://glyph.twistedmatrix.com/2014/02/unyielding.html>`__
803 than the equivalent program using threads.
804
805 Certainly it's not appropriate for every app... but there are a lot of
806 situations where the trade-offs here look pretty appealing.
807
808 There is one downside that's important to keep in mind, though. Making
809 checkpoints explicit gives you more control over how your tasks can be
810 interleaved – but with great power comes great responsibility. With
811 threads, the runtime environment is responsible for making sure that
812 each thread gets its fair share of running time. With Trio, if some
813 task runs off and does stuff for seconds on end without executing a
814 checkpoint, then... all your other tasks will just have to wait.
815
816 Here's an example of how this can go wrong. Take our :ref:`example
817 from above <tutorial-example-tasks-intro>`, and replace the calls to
818 :func:`trio.sleep` with calls to :func:`time.sleep`. If we run our
819 modified program, we'll see something like:
820
821 .. code-block:: none
822
823 parent: started!
824 parent: spawning child1...
825 parent: spawning child2...
826 parent: waiting for children to finish...
827 child2 started! sleeping now...
828 [... pauses for 1 second ...]
829 child2 exiting!
830 child1: started! sleeping now...
831 [... pauses for 1 second ...]
832 child1: exiting!
833 parent: all done!
834
835 One of the major reasons why Trio has such a rich
836 :ref:`instrumentation API <tutorial-instrument-example>` is to make it
837 possible to write debugging tools to catch issues like this.
838
839
840 Networking with Trio
841 --------------------
842
843 Now let's take what we've learned and use it to do some I/O, which is
844 where async/await really shines.
845
846 The traditional toy application for demonstrating network APIs is an
847 "echo server": a program that awaits arbitrary data from remote clients,
848 and then sends that same data right back. (Probably a more relevant example
849 these days would be an application that does lots of concurrent HTTP
850 requests, but for that `you need an HTTP library
851 <https://github.com/python-trio/trio/issues/236#issuecomment-310784001>`__
852 such as `asks <https://asks.readthedocs.io>`__, so we'll stick
853 with the echo server tradition.)
854
855 In this tutorial, we present both ends of the pipe: the client, and the
856 server. The client periodically sends data to the server, and displays its
857 answers. The server awaits connections; when a client connects, it recopies
858 the received data back on the pipe.
859
860
861 An echo client
862 ~~~~~~~~~~~~~~
863
864
865 To start with, here's an example echo *client*, i.e., the program that
866 will send some data at our echo server and get responses back:
867
868 .. _tutorial-echo-client-example:
869
870 .. literalinclude:: tutorial/echo-client.py
871 :linenos:
872
873 Note that this code will not work without a TCP server such as the one
874 we'll implement below.
875
876 The overall structure here should be familiar, because it's just like
877 our :ref:`last example <tutorial-example-tasks-intro>`: we have a
878 parent task, which spawns two child tasks to do the actual work, and
879 then at the end of the ``async with`` block it switches into full-time
880 parenting mode while waiting for them to finish. But now instead of
881 just calling :func:`trio.sleep`, the children use some of Trio's
882 networking APIs.
883
884 Let's look at the parent first:
885
886 .. literalinclude:: tutorial/echo-client.py
887 :linenos:
888 :lineno-match:
889 :pyobject: parent
890
891 First we call :func:`trio.open_tcp_stream` to make a TCP connection to
892 the server. ``127.0.0.1`` is a magic `IP address
893 <https://en.wikipedia.org/wiki/IP_address>`__ meaning "the computer
894 I'm running on", so this connects us to whatever program on the local
895 computer is using ``PORT`` as its contact point. This function returns
896 an object implementing Trio's :class:`~trio.abc.Stream` interface,
897 which gives us methods to send and receive bytes, and to close the
898 connection when we're done. We use an ``async with`` block to make
899 sure that we do close the connection – not a big deal in a toy example
900 like this, but it's a good habit to get into, and Trio is designed to
901 make ``with`` and ``async with`` blocks easy to use.
902
903 Finally, we start up two child tasks, and pass each of them a
904 reference to the stream. (This is also a good example of how
905 ``nursery.start_soon`` lets you pass positional arguments to the
906 spawned function.)
907
908 Our first task's job is to send data to the server:
909
910 .. literalinclude:: tutorial/echo-client.py
911 :linenos:
912 :lineno-match:
913 :pyobject: sender
914
915 It uses a loop that alternates between calling ``await
916 client_stream.send_all(...)`` to send some data (this is the method
917 you use for sending data on any kind of Trio stream), and then
918 sleeping for a second to avoid making the output scroll by too fast on
919 your terminal.
920
921 And the second task's job is to process the data the server sends back:
922
923 .. literalinclude:: tutorial/echo-client.py
924 :linenos:
925 :lineno-match:
926 :pyobject: receiver
927
928 It uses an ``async for`` loop to fetch data from the server.
929 Alternatively, it could use `~trio.abc.ReceiveStream.receive_some`,
930 which is the opposite of `~trio.abc.SendStream.send_all`, but using
931 ``async for`` saves some boilerplate.
932
933 And now we're ready to look at the server.
934
935
936 .. _tutorial-echo-server-example:
937
938 An echo server
939 ~~~~~~~~~~~~~~
940
941 As usual, let's look at the whole thing first, and then we'll discuss
942 the pieces:
943
944 .. literalinclude:: tutorial/echo-server.py
945 :linenos:
946
947 Let's start with ``main``, which is just one line long:
948
949 .. literalinclude:: tutorial/echo-server.py
950 :linenos:
951 :lineno-match:
952 :pyobject: main
953
954 What this does is call :func:`serve_tcp`, which is a convenience
955 function Trio provides that runs forever (or at least until you hit
956 control-C or otherwise cancel it). This function does several helpful
957 things:
958
959 * It creates a nursery internally, so that our server will be able to
960 handle multiple connections at the same time.
961
962 * It listens for incoming TCP connections on the specified ``PORT``.
963
964 * Whenever a connection arrives, it starts a new task running the
965 function we pass (in this example it's ``echo_server``), and passes
966 it a stream representing that connection.
967
968 * When each task exits, it makes sure to close the corresponding
969 connection. (That's why you don't see any ``async with
970 server_stream`` in the server – :func:`serve_tcp` takes care of this
971 for us.)
972
973 So :func:`serve_tcp` is pretty handy! This part works pretty much the
974 same for any server, whether it's an echo server, HTTP server, SSH
975 server, or whatever, so it makes sense to bundle it all up together in
976 a helper function like this.
977
978 Now let's look at ``echo_server``, which handles each client
979 connection – so if there are multiple clients, there might be multiple
980 calls to ``echo_server`` running at the same time. This is where we
981 implement our server's "echo" behavior. This should be pretty
982 straightforward to understand, because it uses the same stream
983 functions we saw in the last section:
984
985 .. literalinclude:: tutorial/echo-server.py
986 :linenos:
987 :lineno-match:
988 :pyobject: echo_server
989
990 The argument ``server_stream`` is provided by :func:`serve_tcp`, and
991 is the other end of the connection we made in the client: so the data
992 that the client passes to ``send_all`` will come out here. Then we
993 have a ``try`` block discussed below, and finally the server loop
994 which alternates between reading some data from the socket and then
995 sending it back out again (unless the socket was closed, in which case
996 we quit).
997
998 So what's that ``try`` block for? Remember that in Trio, like Python
999 in general, exceptions keep propagating until they're caught. Here we
1000 think it's plausible there might be unexpected exceptions, and we want
1001 to isolate that to making just this one task crash, without taking
1002 down the whole program. For example, if the client closes the
1003 connection at the wrong moment then it's possible this code will end
1004 up calling ``send_all`` on a closed connection and get a
1005 :exc:`BrokenResourceError`; that's unfortunate, and in a more serious
1006 program we might want to handle it more explicitly, but it doesn't
1007 indicate a problem for any *other* connections. On the other hand, if
1008 the exception is something like a :exc:`KeyboardInterrupt`, we *do*
1009 want that to propagate out into the parent task and cause the whole
1010 program to exit. To express this, we use a ``try`` block with an
1011 ``except Exception:`` handler.
1012
1013 In general, Trio leaves it up to you to decide whether and how you
1014 want to handle exceptions, just like Python in general.
1015
1016
1017 Try it out
1018 ~~~~~~~~~~
1019
1020 Open a few terminals, run ``echo-server.py`` in one, run
1021 ``echo-client.py`` in another, and watch the messages scroll by! When
1022 you get bored, you can exit by hitting control-C.
1023
1024 Some things to try:
1025
1026 * Open several terminals, and run multiple clients at the same time,
1027 all talking to the same server.
1028
1029 * See how the server reacts when you hit control-C on the client.
1030
1031 * See how the client reacts when you hit control-C on the server.
1032
1033
1034 Flow control in our echo client and server
1035 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1036
1037 Here's a question you might be wondering about: why does our client
1038 use two separate tasks for sending and receiving, instead of a single
1039 task that alternates between them – like the server has? For example,
1040 our client could use a single task like:
1041
1042 .. code-block:: python
1043
1044 # Can you spot the two problems with this code?
1045 async def send_and_receive(client_stream):
1046 while True:
1047 data = ...
1048 await client_stream.send_all(data)
1049 received = await client_stream.receive_some()
1050 if not received:
1051 sys.exit()
1052 await trio.sleep(1)
1053
1054 It turns out there are two problems with this – one minor and one
1055 major. Both relate to flow control. The minor problem is that when we
1056 call ``receive_some`` here we're not waiting for *all* the data to be
1057 available; ``receive_some`` returns as soon as *any* data is available. If
1058 ``data`` is small, then our operating systems / network / server will
1059 *probably* keep it all together in a single chunk, but there's no
1060 guarantee. If the server sends ``hello`` then we might get ``hello``,
1061 or ``he`` ``llo``, or ``h`` ``e`` ``l`` ``l`` ``o``, or ... bottom
1062 line, any time we're expecting more than one byte of data, we have to
1063 be prepared to call ``receive_some`` multiple times.
1064
1065 And where this would go especially wrong is if we find ourselves in
1066 the situation where ``data`` is big enough that it passes some
1067 internal threshold, and the operating system or network decide to
1068 always break it up into multiple pieces. Now on each pass through the
1069 loop, we send ``len(data)`` bytes, but read less than that. The result
1070 is something like a memory leak: we'll end up with more and more data
1071 backed up in the network, until eventually something breaks.
1072
1073 .. note:: If you're curious *how* things break, then you can use
1074 `~trio.abc.ReceiveStream.receive_some`\'s optional argument to put
1075 a limit on how many bytes you read each time, and see what happens.
1076
1077 We could fix this by keeping track of how much data we're expecting at
1078 each moment, and then keep calling ``receive_some`` until we get it all:
1079
1080 .. code-block:: python
1081
1082 expected = len(data)
1083 while expected > 0:
1084 received = await client_stream.receive_some(expected)
1085 if not received:
1086 sys.exit(1)
1087 expected -= len(received)
1088
1089 This is a bit cumbersome, but it would solve this problem.
1090
1091 There's another problem, though, that's deeper. We're still
1092 alternating between sending and receiving. Notice that when we send
1093 data, we use ``await``: this means that sending can potentially
1094 *block*. Why does this happen? Any data that we send goes first into
1095 an operating system buffer, and from there onto the network, and then
1096 another operating system buffer on the receiving computer, before the
1097 receiving program finally calls ``receive_some`` to take the data out
1098 of these buffers. If we call ``send_all`` with a small amount of data,
1099 then it goes into these buffers and ``send_all`` returns immediately.
1100 But if we send enough data fast enough, eventually the buffers fill
1101 up, and ``send_all`` will block until the remote side calls
1102 ``receive_some`` and frees up some space.
1103
1104 Now let's think about this from the server's point of view. Each time
1105 it calls ``receive_some``, it gets some data that it needs to send
1106 back. And until it sends it back, the data that is sitting around takes up
1107 memory. Computers have finite amounts of RAM, so if our server is well
1108 behaved then at some point it needs to stop calling ``receive_some``
1109 until it gets rid of some of the old data by doing its own call to
1110 ``send_all``. So for the server, really the only viable option is to
1111 alternate between receiving and sending.
1112
1113 But we need to remember that it's not just the client's call to
1114 ``send_all`` that might block: the server's call to ``send_all`` can
1115 also get into a situation where it blocks until the client calls
1116 ``receive_some``. So if the server is waiting for ``send_all`` to
1117 finish before it calls ``receive_some``, and our client also waits for
1118 ``send_all`` to finish before it calls ``receive_some``,... we have a
1119 problem! The client won't call ``receive_some`` until the server has
1120 called ``receive_some``, and the server won't call ``receive_some``
1121 until the client has called ``receive_some``. If our client is written
1122 to alternate between sending and receiving, and the chunk of data it's
1123 trying to send is large enough (e.g. 10 megabytes will probably do it
1124 in most configurations), then the two processes will `deadlock
1125 <https://en.wikipedia.org/wiki/Deadlock>`__.
1126
1127 Moral: Trio gives you powerful tools to manage sequential and
1128 concurrent execution. In this example we saw that the server needs
1129 ``send`` and ``receive_some`` to alternate in sequence, while the
1130 client needs them to run concurrently, and both were straightforward
1131 to implement. But when you're implementing network code like this then
1132 it's important to think carefully about flow control and buffering,
1133 because it's up to you to choose the right execution mode!
1134
1135 Other popular async libraries like `Twisted
1136 <https://twistedmatrix.com/>`__ and :mod:`asyncio` tend to paper over
1137 these kinds of issues by throwing in unbounded buffers everywhere.
1138 This can avoid deadlocks, but can introduce its own problems and in
1139 particular can make it difficult to keep `memory usage and latency
1140 under control
1141 <https://vorpus.org/blog/some-thoughts-on-asynchronous-api-design-in-a-post-asyncawait-world/#three-bugs>`__.
1142 While both approaches have their advantages, Trio takes the position
1143 that it's better to expose the underlying problem as directly as
1144 possible and provide good tools to confront it head-on.
1145
1146 .. note::
1147
1148 If you want to try and make the deadlock happen on purpose to see
1149 for yourself, and you're using Windows, then you might need to
1150 split the ``send_all`` call up into two calls that each send half of
1151 the data. This is because Windows has a `somewhat unusual way of
1152 handling buffering
1153 <https://stackoverflow.com/questions/28785626/what-is-the-size-of-a-socket-send-buffer-in-windows>`__.
1154
1155
1156 When things go wrong: timeouts, cancellation and exceptions in concurrent tasks
1157 -------------------------------------------------------------------------------
1158
1159 TODO: give an example using :func:`fail_after`
1160
1161 TODO: explain :exc:`Cancelled`
1162
1163 TODO: explain how cancellation is also used when one child raises an
1164 exception
1165
1166 TODO: maybe a brief discussion of :exc:`KeyboardInterrupt` handling?
1167
1168 ..
1169 Timeouts
1170 --------
1171
1172 XX todo
1173
1174 timeout example:
1175
1176 .. code-block:: python
1177
1178 async def counter():
1179 for i in range(100000):
1180 print(i)
1181 await trio.sleep(1)
1182
1183 async def main():
1184 with trio.fail_after(10):
1185 await counter()
1186
1187 you can stick anything inside a timeout block, even child tasks
1188
1189 [show something like the first example but with a timeout – they
1190 both get cancelled, the cancelleds get packed into an ExceptionGroup, and
1191 then the timeout block catches the cancelled]
1192
1193 brief discussion of KI?
1194 tasks-with-trace.py + control-C is pretty interesting
1195 or maybe leave it for a blog post?