Coding Style for Urwid Library
This is meant as a guide for people contributing code to Urwid itself. Of course you may choose to follow it for your own code that uses Urwid if you are aiming for the same level of Python compatibility.
Urwid's current version aims to be compatible with Python versions 2.4 - 3.2. These guidelines will help you write Python 2 code that will across those versions (with the help of 2to3)
PEP8
For the most part Urwid code follows PEP8, the Style Guide for Python Code. The main exception is that wrapped long lines are indented with 4 extra spaces instead of aligning to the previous parentheses, bracket or brace.
from __future__
We avoid use of from __future__ imports in Urwid.
This makes the code as much like normal Python 2 code as possible, allows people to easily move code in and out of the library and avoids surprising behaviour.
Strings and Binary Data
The str type becomes Unicode in Python 3, so we have to deal with three different types now:
- Unicode strings
- 8-bit strings in Python 2 that become Unicode in Python 3
- Binary data
Unicode strings should be used for all text data in Urwid (mostly in example programs, but also in widgets that come with some default text).
- Use u"My textual data" for literal text data everywhere.
Certain types of data (__repr__ return values, symbol names, function documentation..) are an 8-bit strings in Python 2 but becomes Unicode text in Python 3. Urwid also uses this type for a number of "defined" constants.
- Use "normal literal strings" for this data everywhere
- Exception: for "defined" constants use the variable names when available, eg. widget.FLOW instead of "flow"
Binary data is used in Canvas objects and when sending updates to the user's terminal.
from urwid.compat import B, bytes
- Use B("bindata\x00\x42\xfe") for literal binary data
- Use bytes() for an empty binary string (eg. for joining a list of binary values)
- Use bytes().ljust(x) for x "space" characters as binary data
Unit Tests and Doctests
When adding new code always include doctests (and documention!) where appropriate and unit tests for simple validation any tricky corner cases. Add unit tests to urwid/tests.py and when creating a new module add it to the list of doctest modules in the same file. To run the tests run:
python setup.py test
