In this other post you gave a great tip on how to show a “Please wait” notification. Works perfectly.
My question is how/why does this work?
with Notification("Unit tests running..."):
import test_me
test_me.run_tests()
You don’t show() the notification or anything. How does it even display? And why does it disappear when the block ends?
EDIT - I just read this in the documentation, I suppose I don’t really need to know how it works. I shall just accept the magic
If you use a notification in a with block, it will be displayed as long as the body of the block is still running. It will then disappear.
1 Like
The magic is a really cool Python feature called “context managers” (alternative name: “Things you can put in a with
block”). A with
block provides a way of automatically tidying up something at the end of a block of code, whether you exited normally, by returning, or by throwing an exception. In Anvil, we use them for things like auto-closing Notifications, and atomic transactions in data tables.
If you want to dig into them a little bit more, here’s a page with a more detailed exploration of how they work (and even how to build your own): http://effbot.org/zone/python-with-statement.htm
Very interesting, thanks.
So the Notification box magically showing and hiding - is that something you do in the background in the __enter__ and __exit__ methods?
Yes! On a Notification, we show on __enter__
and hide on __exit__
.
Very cool.
Are there any other controls that exhibit interesting traits when used in this (or any other unusual) way, that might not be immediately obvious to us?
We try to make sure it’s all in the documentation!
https://anvil.works/doc
Yes, that is very true.
My issue is I don’t always recognise what I’m looking at. I saw that “with” paragraph but didn’t make the connection that it could be used in that way. I’m getting old, you know …
I’m putting together a little “Anvil Cookbook” of what I consider useful snippets and techniques. I’ll stuff it in the appropriate section of this forum for anyone who’s interested (and for those cleverer than me to correct/improve/snigger at).
Thank you for posting this its perfect just what I needed