Author's Bio: Anton Mamaenko

Tuesday, November 16, 2010

Flow control using Logical expressions in Python

Python allows for a very simple assertion-like syntax for controlling the flow:

def RaiseException(msg): raise Exception(msg)

x = GetSomeObject() or RaiseException("SomeObject not found")


Python does not allow putting the raise keyword in the logical expression, so the RaiseException(...) wrapper is used.

The trick is based on the fact that None is treated as False, and any valid pointer as True within logical expression. This simplifies the logic, and makes the code more readable.

The use of assertions, i.e. checking if an object pointer is not NULL (None in Python), is one of good practices in C++. But in Python with its garbage collector, and different coding approach it is rarely used. Nevertheless - if one needs assertions a lot, for example working with COM objects via win32com extensions - here is a simple way of using them.

No comments:

Post a Comment

Search This Blog