easy question on parsing python: "is not None"

Stefan Schwarzer sschwarzer at sschwarzer.net
Fri Aug 6 15:37:04 CEST 2010

Hi DG,

On 2010-08-06 14:28, DG wrote:
> I've always thought of it as you don't compare strings with "is", you
> *should* use ==  The reasoning is that you don't know if that string
> instance is the only one in memory.  I've heard as an implementation
> detail, since strings are immutable, that Python will only create one
> actual instance and just assign new references to it (your first x is
> y example), but to compare equality it just makes sense to use "==",
> not to ask if it is the same object in memory.

Yes, you'd usually use == to compare strings. The use in the
post presumably was to show the behavior when you use `is`;
I guess it wasn't meant as an example for production code. :)

I can imagine a case where you might want to compare a
string with `is`:

    FORWARD = "forward"
    BACKWARD = "backward"


    def func(direction=FORWARD):
        if direction is FORWARD:
        elif direction is BACKWARD:

in case you expect people to specifically use the constants
you provided in the module. Here, the fact that FORWARD
actually is the string "forward" might be considered an
implementation detail. Using a string instead of an
`object()` has the advantage that it makes usage in error
messages easier.

Actually, I've never seen such a use, as far as I remember.
What do other people here think? Is the code above, which
compares strings with `is`, bad style, and if yes, why? How
would you write the code instead?

> Plus, I believe the
> "==" operator will check if the variables point to the same object.

No, that's what `is` is for.

> Using is/is not with None works well, because I believe there will
> always only be 1 None object.

Yes, and it avoids subtle bugs if someone overwrites `__eq__`
in some class:

    >>> class AlwaysEqual(object):
    ...     def __eq__(self, other):
    ...         return True
    >>> always_equal = AlwaysEqual()
    >>> always_equal == None
    >>> None == always_equal
    >>> always_equal is None


More information about the Python-list mailing list