[Python-ideas] a in x or in y
Andrew Barnert
abarnert at yahoo.com
Thu Feb 13 05:41:25 CET 2014
On Feb 12, 2014, at 15:55, Carl Meyer <carl at oddbird.net> wrote:
> On 02/12/2014 02:12 PM, Ram Rachum wrote:
>> What do you think about adding this to Python:
>>
>> 'whatever a long string' in x or in y
>>
>> I've often wished for this because the current way is quite verbose:
>>
>> 'whatever a long string' in x or 'whatever a long string' in y
For future reference, using expression_with_side_effects() instead of 'whatever a long string' would be a more compelling use case. With a long string, it's inconvenient and ugly to repeat it; with an expression with side effects, it's all that plus incorrect to boot.
But of course the same solutions still work.
> Except you'd never actually do that, you'd just put the long string in a
> variable. Or the other option:
>
> any('whatever a long string' in i for i in [x, y])
Or, if you're doing this so often that even this is too verbose:
def in_any(element, *containers):
return any(element in container for container in containers)
in_any('whatever a long string', x, y, z, w)
If you're not doing it often enough for in_any to become familiar, then you didn't have a problem to solve in the first place. :)
More information about the Python-ideas
mailing list