I ran into an interesting issue with my Windows development machine when trying to test a Flask web app. This was due to werkzeug running the simple web server for flask that is created when you us app.run(). The error had me confused at first, as it has nothing to do with what I was changing at the time: TypeError: OpenKey() argument 2 must be str without null characters or None, not str I tracked back through the stack to see that werkzeug is looking at the Windows Registry.
I’m using a Raspberry Pi 3 as the CPU in custom burn-in carts for cycling our Android tablets. It is hard to beat the 7” touch display using a Flask front end for quick development. The carts often have power connected and disconnected when moved around. We are also using a network inside of the carts for talking with tablets under test and need to bring this up each time we move carts and cycle power.
Enums are new with Python 3.4 and PEP 435, but have been backported. At first, I saw more trouble than benefit from Python Enums. They are typically used for type safety, and this isn’t really enforceable in Python. But, since they are a class, you can add additional functionality to them. This gives them more usefulness than I previously thought. It isn’t easy to store data with them in most languages.
One of the best ways to become efficient with Python is to really learn the standard libraries. However, do this with understanding that some are included for base functionality or compatibility, but have been superseded by better packages in PyPi. Requests over urllib2 is a great example of this. By being outside of Python, these packages can iterate faster and not be dependent on Python releases. Collections is not one that needed replacement.
You may have seen if __name__ == '__main__': at the bottom of a script. Why is this there and what does it mean? First, a python file is a module. They can be combined into a directory module and this is what is being done when you see an __init__.py file in the folder. We will get there in a little while, but first we will cover a little more than just __name__.
Iterators and Generators are two mechanisms for providing data to cycle through in Python. The difference is if the data is already in memory and we iterate along it, or if we are generating it as we go. The names actually make sense. These turn out to be very similar and just differ in execution. One is better if you already have a class. The other is a little simpler.
Context managers were added to Python with PEP 343. This allows proper handling of resources without worrying about missing something in your try/finally code. If you are not opening files using a context manager, you are most likely doing it wrong. Looking at opening a file and what could go wrong, will show how context managers make programming both more robust and simpler. The operation can be broken into 3 sections of code.