is operator

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Mar 10 12:36:53 EDT 2008


On Mon, 10 Mar 2008 07:39:25 -0700, Gary Herron wrote:

> If either is a surprise, then understand that the "is" operator should
> probably *never* be used with immutable types.

Carl Banks has already mentioned testing for None with "is". The standard 
idiom for using mutable default arguments goes something like this:

def foo(arg=None):
    if arg is None:
        arg = []
    do_something_with(arg)


Another standard idiom that requires "is":

sentinel = object()  # a special value that isn't None
...
if something is sentinel:
    blah blah blah


Mutable or immutable, it makes no difference: "is" is for testing 
identity, == is for testing equality. If you need to test for identity, 
use "is". If you need to test for equality, use ==.



-- 
Steven





More information about the Python-list mailing list