testing for valid reference: obj vs. None!=obs vs. obj is not None

BJörn Lindqvist bjourne at gmail.com
Mon Sep 4 20:53:17 EDT 2006


> I have a reference to certain objects. What is the most pythonic way to
> test for valid reference:
>
>         if obj:
>
>         if None!=obs:
>
>         if obj is not None:

The third way is the most precise way. It is often used in combination
with default arguments.

def __init__(self, amount = None):
    if amount is not None:
        self.amount = amount
    else:
        self.amount = self.calc_amount()

However, the first way is shorter and more concise. It really depends
on what obj is supposed to be and where you get obj from. If it is a
database and obj is an instance:

obj = db.get("sometable", id = 33)

(assuming db.get returns None if the object isn't found) Then "if
obj:" clearly is the right test. In general, I think "If obj:" is the
right answer, except when dealing with default arguments. And you must
be aware that some objects, like 0, [] or {} evaluate to False -- it
is possible that that could create some subtle bugs.

-- 
mvh Björn



More information about the Python-list mailing list