None in string => TypeError?

Paul Sokolovsky pmiscml at gmail.com
Mon Jun 9 11:57:28 EDT 2014


Hello,

On Mon, 9 Jun 2014 08:34:42 -0700 (PDT)
Roy Smith <roy at panix.com> wrote:

> We noticed recently that:
> 
> >>> None in 'foo'
> 
> raises (at least in Python 2.7)
> 
> TypeError: 'in <string>' requires string as left operand, not NoneType
> 
> This is surprising.  The description of the 'in' operatator is, 'True
> if an item of s is equal to x, else False	'.  From that, I
> would assume it behaves as if it were written:
> 
> for item in iterable:
>     if item == x:
>         return True
> else:
>     return False
> 
> why the extra type check for str.__contains__()?  That seems very
> unpythonic.  Duck typing, and all that. -- 

This is very Pythonic, Python is strictly typed language. There's no
way None could possibly be "inside" a string, so if you're trying to
look for it there, you're doing something wrong, and told so.

Also, it's not "extra check", it's "extra checks less", just consider
that "in" operator just checks types of its arguments for sanity once
at the start, and then just looks for a substring within string. You
suggest that it should check for each element type in a loop, which is
great waste, as once again, nothing but a string can be inside another
string.


-- 
Best regards,
 Paul                          mailto:pmiscml at gmail.com



More information about the Python-list mailing list