There are a whole bunch of underscores in Python. If you are new to Python, this may seem weird. There is a reason behind the flatness. There are even special names for them, under when you have a single underscore and dunder when two underscores are used (for double underscore). Unders There are many uses of single underscores in Python. We will hit a few common and easy to explain right away and get them over with.
If you came directly to this article, you might want to read my previous on in this series with the link at the bottom. We discussed the dangers of using mutable values for defaults in a function parameter. In this article I’ll discuss two things: using mutable defaults for good and decorators. In the end, combining these together. Using the default mutable for good In developing a Python workflow for a custom system, I’m interfacing with custom hardware to measure current and temperature.
Default arguments in Python allow you to make complex functions very easy to use. They can be called with mostly defaults or called with as much configuration as needed. This comes with a gotcha for those getting started in this. If you use mutable data structures as defaults, things don’t behave exactly as you would expect. However, before we start, lets cover some things you may not know that I will use in the code.
Python 3 Strings The handling of strings was one of the major breaking change between Python 2 and 3. Python 2 was easy for English speaking folks that could live in 8-bit ASCII land. It was easy to use a string as a sequence of bytes when doing binary transfer. However, turning 8-bit ASCII into Unicode was a little daunting. With Python 3, all strings are Unicode. To get a bytes object as a string would be in Python 2, you prefix a string with a b as in b'bytes object with \xf4 <- high 8-bit character'.
In my current role, I don’t do much mentoring to other programmers at a language specific level. Most of my job is isolated somewhat and I’m the only serious Python programmer at the company. I can offer insight in architecture, DB design and other pieces relative to our Android, iOS, and Web applications, but not Python. So I decided to capture some of my thoughts about what I would tell a new Python programmer, to help them progress into a successful Pythonista faster.
The Bencode format is an interesting design. It is byte based, which makes it safe from big-endian and little-endian translations. Somewhere when reading about how torrents worked, I got looking at their file format. As far as I know, the Bencode format isn’t used on anything but torrent files. The format is pretty simple, with only 4 different data structures: Byte String, Integer, List, and Dictionary. Bencode Basics Byte String This is formatted as [integer length]:[byte string].