Tuesday, 5 February 2013

Coding Gold Dust: How to write an infinite loop in Python

One of the coding style issues that has come up more than often on the Raspberry Pi forum is: how to write an infinite loop in Python?

For obvious reasons, many RPi examples are about hardware or network interfacing, and often these examples are derived from C language code. Interfacing, due to it's event-driven nature (especially when reading something), warrants the use of an infinite loop - or well, an event-loop to be more precise.

In plain C, there is no boolean data type but instead anything 'non zero' evaluates to 'true'. Hence an infinite loop in C is typically (and rightfully so) implemented as a while loop like this:
while (1) {
    printf("Hello, world!\n");
}

It seems that this does work in Python as well:
while 1:
    print "Hello, world!"

By definition a while loop continues execution as long as the condition evaluates to true. So practically any expression that evaluates to true could be used:
while (1 == 1):
    ...
test = "true"
while (test == "true"):
    ...
while (1 < 2):
    ...
However, it should be obvious that these are neither beautiful, explicit, simple, readable nor obvious - which are what 'The Zen of Python' lists as 'guiding design principles' for Python, and could be taken as guiding principles for any Python code. In addition, especially the string comparison might incur a performance hit.

Many programming languages do define proper boolean types. For example Java has a data type called boolean and defines the values true and false for that type. Hence our loop in Java would be:
while (true) {
    System.out.println("Hello, world!");
}
Python too defines a class bool, which can have two values True and False. And because there is a boolean data type, it should make perfect sense to use that and (for consistency) only that to implement an infinite loop:
while True:
    print "Hello, world!"
I rest my case ;)

In addition to The Zen of Python, there is a Python Style Guide available - definitely worth a read.

P.S. Thanks for fellow RPI forum user alexeames for the idea of 'Gold Dust' :)

No comments:

Post a Comment

Note: only a member of this blog may post a comment.