None in string => TypeError?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Jun 9 12:14:16 EDT 2014


On Mon, 09 Jun 2014 18:57:28 +0300, Paul Sokolovsky wrote:

> 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, 

Then `None in some_string` could immediately return False, instead of 
raising an exception.


> so if you're trying to look
> for it there, you're doing something wrong, and told so.

This, I think, is the important factor. `x in somestring` is almost 
always an error if x is not a string. If you want to accept None as well:

x is not None and x in somestring 

does the job nicely.


-- 
Steven D'Aprano
http://import-that.dreamwidth.org/



More information about the Python-list mailing list