[Python-ideas] a in x or in y

Steven D'Aprano steve at pearwood.info
Thu Feb 13 11:57:17 CET 2014


On Wed, Feb 12, 2014 at 01:12:17PM -0800, Ram Rachum wrote:
> Hi,
> 
> What do you think about adding this to Python:
> 
>     'whatever a long string' in x or in y

I like it. In natural language, people often say things like:

    my keys are in the car or in my pocket

which fools them into writing:

    keys in car or pocket

which does the wrong thing. Chained "in" comparisons is a natural 
extension to Python's already natural language-like syntax. Python 
already has other chained comparisons. Being able to write:

    keys in car or in pocket

feels natural and right to me. (We can't *quite* match the human idiom 
where the second "in" is left out, but one can't have everything.)

This is particularly useful when there are side-effects involved:

    something_with_side_effects() in this and in that or in other


I'm not usually one for introducing syntax just to avoid a temporary 
variable or extra line:

    temp = something_with_side_effects()
    temp in this and temp in that or temp in other


but I think that chained comparisons are one of Python's 
best syntactic features, and this just extends it to "in".

The only two concerns I have are:

- given the restrictions on the parser, is this even possible? and

- the difference between "x in y and z" and "x in y and in z" is quite 
  subtle, and hence may be an unfortunately common source of errors.


So a tentative +1 on the idea.



-- 
Steven


More information about the Python-ideas mailing list