You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Add collection of worked examples to tutorial #472
We should refactor the tutorial into an initial part that's similar to what we have now, or the middle part of my talk, and then a collection of examples that also serve as excuses to go into more depth on particular topics.
I expect the list will grow over time, but here are some ideas. (Actually the main reason I'm filing this is to have a place collect these so I don't lose them.)
The current tracing demo should move here. It's a good intro to trio introspection and to co-op concurrency, but having it in the main tutorial like it is now is a big blob of text for folks to wade through if they already know this stuff. (We can/should link to it from the async/await intro though.)
Happy eyeballs (for people who saw the talk but want a text version; as a demo of passing nursery objects around; ...)
Custom nursery, like a race function or ignore-errors nursery (maybe both)
Some standard stuff like echo server, proxy, fast web spider, ... Whatever doesn't end up in the main tutorial. (We could have echo server and TCP proxy as two examples, then show how to run them both within a single process as an example of implementing multi-protocol servers... and also to show off how proxy_one_way can be re-used for both! Maybe the proxy should demonstrate mirroring localhost:12345 to httpbin:80, so people can try it out with their web browsers?)
trio-asyncio example?
nursery.start
Possibly some of these could be combined or form sequences, eg echo server -> catch all handler -> nursery.start
Reacted by Xavier G. Domingo, Joshua Bronson, Dave Hirschfeld, Mathieu PATUREL, Kyle Lawlor-Bagcal and Honglei
Oh duh, here's another one: an example of implementing a custom protocol, by combining a sansio protocol with the stream interface. (Probably some simple line-oriented or netstring-oriented thing. This is one of the motivations for why I started working on sansio_toolbelt. I should make it actually usable...)
A walkthrough for converting a sync protocol to Trio might also make sense.
WRT trio-asyncio: maybe simply refer to it. I do need to add some example that shows how to convert from asyncio to trio-asyncio to trio, and how that improves the code. ;-)
@N-Coder pointed out that there are a number of useful "asyncio cookbook" type articles floating around, and probably trio would benefit from something that serves a similar role. I think that's the same idea in this thread, but the examples are potentially helpful:
As mentioned in #537, a UDP example would be good. This would also be a good way to demonstrate using trio.socket directly.
The example in that comment thread is kind of boring. Doing a dns query or ntp query would be more interesting. [edit: see notes-to-self/ntp-example.py for an ntp query example.]
It would be good to have an example that discusses the subtleties of aclose: in general, cancellation means "stop what you're doing ASAP and clean up". But if what you're doing is cleaning up... what does that mean? Basically just "clean up ASAP" → graceful vs forceful close.
Maybe this would fit in with an example that wraps a stream in a higher-level protocol object, so we have to write our own aclose? Esp. if the protocol has some kind of cleanup step.
@smurfix you do need something like an infinite queue for a traditional recursive web scraper, since each consumer task may produce an arbitrary number of new work items. So any finite queue limit could produce a deadlock, when all the consumer tasks are blocked waiting for another consumer task to pull from the queue...
It sounds like I misunderstood @snedeljkovic's problem, and I was assuming a single starting URL, while they actually have the full list of urls up front. So in my gist, I took a kind of shortcut that works for the single URL case, of sending in the original send channel without cloning it, but I didn't point out the tricky bit there, so it wasn't obvious how to correctly generalize to a case with multiple starting urls. That's useful to know for future docs – we need to cover the multiple URLs case and explain the logic behind starting it up correctly.
@snedeljkovic It sounds like you figured out what you need to know? If you still have questions, please let us know – but let's move to a new issue or a thread on trio.discourse.group, so we can focus on your questions properly and keep this thread for tutorial update ideas.
@njsmith Yeah, I realized that but got confused. (It's been a long day.)
In any case, boiling this down to the essentials. you need
an infinite deque
a way to wake up just one worker after the dequeue has run temporarily dry
tell the sender when all workers are done.
Doing this with a lot of cloned senders is perhaps not the most efficient way, thus I have encapsulated the idea in a (somewhat minimal) class, and packaged this version of @snedeljkovic's code in a gist:
@smurfix Wow, thank you very much for the effort! I'm new to this kind of programming so this is of great help to me. @njsmith Sorry, I won't pollute this thread any more ;)
It's good to keep a basic tenet in mind: don't code to the tools you have – that leads to bad design. Code to the tools you need, and build them with the tools you have. Recurse if necessary. ;-)
Quick note about getting started with writing a protocol and wanting to have a way of having pluggable transports (from the Gitter chat just now). For some reason, I couldn't bend my head around this for a while and this might help others:
ahh, I see. So the idea is that you implement your protocol as a function or class that takes a Stream object, and uses its methods to send/receive bytes and your code does whatever higher-level thing it wants to with those bytes
so maybe you'd do like my_proto_over_memory_stream = MyProtocol(memory_stream) or my_proto_over_tcp = MyProtocol(tcp_stream)
composition, not inheritance
#1141 really helped me a lot and I think it would be great to include an example of thinking about providing a open_foo function when trying to design an API for whatever objects you expose to the end-user.
A: the general pattern is to first set up a a callback that will call trio.hazmat.reschedule, and then call trio.hazmat.wait_task_reschedule to put the task to sleep until the callback comes in or the operation is cancelled
I'd like to see a table mapping as many Go idioms to Trio idioms as possible, for those like me who have worked with Go.
For starters (probably not entirely correct as I'm fairly new to Trio):
ch := make(chan X) | send, recv = trio.open_memory_channel(0)
ch := make(chan X, 37) | send, recv = trio.open_memory_channel(37)
close(ch) | send.close(); recv.close()
x = <-ch | x = await recv.receive()
ch <- X | await send.send(X)
done := make(chan any) | with trio.open_nursery() as n:
go func(done) | n.start_soon(func)
<-done |
select { case <-ch: XXX } | try: recv.receive_nowait()
| except trio.WouldBlock: pass
| else: XXX
for x := range ch { XXX } | async with recv:
| async for x in recv: XXX
sync.Mutex | trio.Lock
context.Context.Get(XXX) | XXX = contextvars.ContextVar()
@merlinz01 It might make sense indeed to have a table with a few different languages for comparison. I'm not too familiar with Go, but on the Trio side:
It'd be better to say "send.close() or recv.close()". It'd be very odd to close both sides of a channel simultaneously, since those would normally be given to two different tasks, each just responsible for its own end. Looks like closing behaves the same as Go, except that the two sides are independent, and double-closing is just a no-op.
Opening a nursery and starting a single function is equivalent to just await func(), it'd only be useful if doing more than one. Unless you specifically want a new task to be created. Also obviously in the Go example the function could choose to close the channel early or not at all, while in the Trio case that's impossible.
I don't think the select example is equivalent - the docs say it'll block until at least one channel succeeds, but the Trio example is purely synchronous and will only do anything if the channel already has something in its buffer. The way you'd write a select statement is with code like the example in the supervisors section. Create a nursery with a bunch of blocking tasks, then have them cancel the nursery once they succeed. trio-util offers a wait_any() function for when you already have the predicates.
Thanks for the corrections! It's only a couple days since I learned about Trio, so I don't have all the Trio idioms mastered.
For the go func() example, this is more what I was thinking of:
num_workers=5ch:=make(chanMyFunctionResult, num_workers)
// Start the workersforx:=rangenum_workers {
gosend_the_result_over_chan(ch)
}
// Wait for the resultsforx:=rangenum_workers {
res:=<-chifres.err!=nil {
[handleerror]
}
}
close(ch)
vs.
num_workers=5try:
# Start the workerswithtrio.open_nursery() asnursery:
forxinrange(num_workers):
nursery.start_soon(return_the_result)
# implicitly wait for the resultsexcept*Exception:
[handleerror]
For the select example, I think this is more accurate:
Go is super for networking and concurrency, but as it is a compiled language with monolithic binaries it is not quite as flexible. For my project I needed Python's extensibility and dynamic code compilation, so I'm using Trio's async functionality.
I suppose there would be other comparisons besides this that would also be helpful to programmers coming from other languages.
Activity
Fuyukai commentedon Mar 16, 2018
An
asyncio.gather-like (collect the results of all tasks and return the results) would be a good example (as you've said before on Gitter iirc)njsmith commentedon Mar 17, 2018
Oh yeah, good idea! (And we should use the terms
asyncio.gatherandPromise.allin the headline, because people seem to be looking for those.)njsmith commentedon Mar 18, 2018
Oh, see also #421, which is a partial duplicate and has some more discussion of the nursery-based examples.
njsmith commentedon Mar 18, 2018
Oh duh, here's another one: an example of implementing a custom protocol, by combining a sansio protocol with the stream interface. (Probably some simple line-oriented or netstring-oriented thing. This is one of the motivations for why I started working on
sansio_toolbelt. I should make it actually usable...)m-u-xyz commentedon Apr 10, 2018
A walkthrough for converting a sync protocol to Trio might also make sense.
WRT trio-asyncio: maybe simply refer to it. I do need to add some example that shows how to convert from asyncio to trio-asyncio to trio, and how that improves the code. ;-)
nicoddemus commentedon Apr 10, 2018
Would love to see that. 😁
njsmith commentedon Apr 14, 2018
Something like @jab's HTTP CONNECT proxy from #489 (comment) might be interesting too.
(Possibly rewritten to use h11 ;-).)
njsmith commentedon Apr 14, 2018
@oremanj's
as_completedhere might be interesting as the basis for agatherequivalent: https://gitter.im/python-trio/general?at=5ad186345d7286b43a29af53Maybe examples of testing and debugging would be good too. (Testing might just refer to the pytest-trio docs. Which we still need to write...)
oremanj commentedon Apr 26, 2018
There was some more discussion of this on Gitter today, which resulted in rough drafts of reasonable implementations for gather and as_completed both: https://gitter.im/python-trio/general?at=5ae22ef11130fe3d361e4e25
@N-Coder pointed out that there are a number of useful "asyncio cookbook" type articles floating around, and probably trio would benefit from something that serves a similar role. I think that's the same idea in this thread, but the examples are potentially helpful:
njsmith commentedon May 10, 2018
#527 is a common question; we should have something for it.
[-]add collection of worked examples to tutorial[/-][+]Add collection of worked examples to tutorial[/+]njsmith commentedon May 20, 2018
As mentioned in #537, a UDP example would be good. This would also be a good way to demonstrate using
trio.socketdirectly.The example in that comment thread is kind of boring. Doing a dns query or ntp query would be more interesting. [edit: see notes-to-self/ntp-example.py for an ntp query example.]
Add two more notes-to-self files
njsmith commentedon Jul 7, 2018
It would be good to have an example that discusses the subtleties of
aclose: in general, cancellation means "stop what you're doing ASAP and clean up". But if what you're doing is cleaning up... what does that mean? Basically just "clean up ASAP" → graceful vs forceful close.Maybe this would fit in with an example that wraps a stream in a higher-level protocol object, so we have to write our own
aclose? Esp. if the protocol has some kind of cleanup step.19 remaining items
njsmith commentedon Nov 4, 2019
@smurfix you do need something like an infinite queue for a traditional recursive web scraper, since each consumer task may produce an arbitrary number of new work items. So any finite queue limit could produce a deadlock, when all the consumer tasks are blocked waiting for another consumer task to pull from the queue...
It sounds like I misunderstood @snedeljkovic's problem, and I was assuming a single starting URL, while they actually have the full list of urls up front. So in my gist, I took a kind of shortcut that works for the single URL case, of sending in the original send channel without cloning it, but I didn't point out the tricky bit there, so it wasn't obvious how to correctly generalize to a case with multiple starting urls. That's useful to know for future docs – we need to cover the multiple URLs case and explain the logic behind starting it up correctly.
@snedeljkovic It sounds like you figured out what you need to know? If you still have questions, please let us know – but let's move to a new issue or a thread on trio.discourse.group, so we can focus on your questions properly and keep this thread for tutorial update ideas.
m-u-xyz commentedon Nov 4, 2019
@njsmith Yeah, I realized that but got confused. (It's been a long day.)
In any case, boiling this down to the essentials. you need
Doing this with a lot of cloned senders is perhaps not the most efficient way, thus I have encapsulated the idea in a (somewhat minimal) class, and packaged this version of @snedeljkovic's code in a gist:
https://gist.github.com/smurfix/c8efac838e6b39bedc744a6ff8ca4405
Might be a good starting point for a tutorial chapter.
snedeljkovic commentedon Nov 4, 2019
@smurfix Wow, thank you very much for the effort! I'm new to this kind of programming so this is of great help to me.
@njsmith Sorry, I won't pollute this thread any more ;)
m-u-xyz commentedon Nov 5, 2019
It's good to keep a basic tenet in mind: don't code to the tools you have – that leads to bad design. Code to the tools you need, and build them with the tools you have. Recurse if necessary. ;-)
jtrakk commentedon Nov 10, 2019
"How do I"...
decentral1se commentedon Nov 20, 2019
Quick note about getting started with writing a protocol and wanting to have a way of having pluggable transports (from the Gitter chat just now). For some reason, I couldn't bend my head around this for a while and this might help others:
Take a stab at starting the cookbook
Take a stab at starting the cookbook
Take a stab at starting the cookbook
njsmith commentedon Dec 5, 2019
Here's an example that could be turned into a good cookbook tutorial: why TCP flow control can cause deadlocks, and a way to avoid deadlocks when pipelining: https://gist.github.com/njsmith/05c61f6e06ca6a23bef732fbf5e832e6
decentral1se commentedon Jan 13, 2020
#1141 really helped me a lot and I think it would be great to include an example of thinking about providing a
open_foofunction when trying to design an API for whatever objects you expose to the end-user.jtrakk commentedon Feb 8, 2020
From chat
merlinz01 commentedon May 21, 2024
I'd like to see a table mapping as many Go idioms to Trio idioms as possible, for those like me who have worked with Go.
For starters (probably not entirely correct as I'm fairly new to Trio):
TeamSpen210 commentedon May 21, 2024
@merlinz01 It might make sense indeed to have a table with a few different languages for comparison. I'm not too familiar with Go, but on the Trio side:
send.close()orrecv.close()". It'd be very odd to close both sides of a channel simultaneously, since those would normally be given to two different tasks, each just responsible for its own end. Looks like closing behaves the same as Go, except that the two sides are independent, and double-closing is just a no-op.await func(), it'd only be useful if doing more than one. Unless you specifically want a new task to be created. Also obviously in the Go example the function could choose to close the channel early or not at all, while in the Trio case that's impossible.selectexample is equivalent - the docs say it'll block until at least one channel succeeds, but the Trio example is purely synchronous and will only do anything if the channel already has something in its buffer. The way you'd write aselectstatement is with code like the example in the supervisors section. Create a nursery with a bunch of blocking tasks, then have them cancel the nursery once they succeed. trio-util offers await_any()function for when you already have the predicates.merlinz01 commentedon May 22, 2024
Thanks for the corrections! It's only a couple days since I learned about Trio, so I don't have all the Trio idioms mastered.
For the
go func()example, this is more what I was thinking of:vs.
For the select example, I think this is more accurate:
vs.
Go is super for networking and concurrency, but as it is a compiled language with monolithic binaries it is not quite as flexible. For my project I needed Python's extensibility and dynamic code compilation, so I'm using Trio's async functionality.
I suppose there would be other comparisons besides this that would also be helpful to programmers coming from other languages.