We are writing our APIs for Python 3. Python 3 a relatively new version of the language and is not entirely backwards compatible with Python 2. A number of libraries have not yet been ported to this new version. But we believe Python 3 is a good choice for programming our educational kits because it removes many confusing aspects of Python 2.
Why Python 3?
We selected Python 3 for a number of reasons:
- We’re developing educational kits and Python 3 is the Python version selected for the Raspberry Pi educational release.
- Python 3 makes a clear distinction between byte buffers and text strings, which makes doing I/O, working with raw data and working with text strings easier than in Python 2. Python 2 does have a bytes function to create byte buffers that has the same syntax as that of Python 3. However, it has different and confusing behaviour. For example, in Python 3 it acts as you’d expect:
Python 3.1.2 (release31-maint, Dec 9 2011, 20:50:50) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> bytes([1,2,3]) == b'\x01\x02\x03' True
But in Python 2:
Python 2.7.0+ (r27:82500, May 9 2011, 20:29:29) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> bytes([1,2,3]) == b'\x01\x02\x03' False >>> bytes([1,2,3]) == b'\x5b\x31\x2c\x20\x32\x2c\x20\x33\x5d' True
Can you work out why?
- Python 3 has only one, universal, type system/object model, and so avoids confusing errors that can happen in Python 2 when you accidentally forget to declare that your class extends object and then try to use an API that uses the binding protocol or metaclasses. If that last sentence sounds like total gibberish, that demonstrates why we’re using Python 3! We shouldn’t have to expose those advanced language features to new programmers but it’s easy to bump into them by accident in Python 2.
- Many other small quirks and annoyances that remain in Python 2 to ensure backward compatability have been removed, making the language and standard library easier to use.
Unfortunately some popular libraries have not yet been ported to Python 3, including (at the time of writing):
Happily, more libraries are becoming available as time goes by. Those above may have been ported by the time you read this.
Using Python 3 on the Raspberry Pi
Python 3 is not included in the default Raspberry Pi disk image at the moment. You’ll need to install it with the command:
sudo apt-get install python3
Then you use the python3 command to run Python 3 scripts:
To make an executable Python script run with Python 3, the script should start with the following line:
For example, the following script should report that it is running Python 3:
#!/usr/bin/env python3 import sys print(sys.version)