Hello World!
I have been wanting to start a blog for a while… and it’s finally happening! In fact, I’m currently working on my first post about CPython string interning and I hope to publish it in a few days.
Meanwhile, I will leave you with two neat Python tricks I discovered last year in Raymond Hettinger’s PyCon talk: “Transforming Code into Beautiful, Idiomatic Python”.
The ignored
context manager
Suppose you want to create a directory, but this directory might already exist:
Now, let’s define the ignored
context manager as follows:
Finally, this allows you to write:
Nota bene: this is probably not the best example since you can handle this exception better by doing the following:
Still, I am sure you will find appropriate use cases for this context manager.
Read N bytes at a time from a buffer
This time, suppose you want to read 1024 bytes at a time from a file:
Instead, Raymond suggests:
I guess this can be extended to many other uses, be creative!
comments powered by Disqus