How do I check all variables returned buy the functions exists

Peter Otten __peter__ at web.de
Wed Sep 20 05:14:42 EDT 2017


Bill wrote:

> Robin Becker wrote:
>> On 16/09/2017 01:58, Steve D'Aprano wrote:
>> ........
>>>
>>> If you want to test for None specifically:
>>>
>>> if any(v is None for v in values):
>>>      print "at least one value was None"
>>>
>> .......
>>
>> for some reason that seems slow on my machine when compared with
>>
>> if None in values:
>>    .....
>>
>>
> This does not seem particularly surprising.  "None in values" is known
> as soon as None is found.
> In "any(v is None for v in values)",  "any" probably isn't called until
> its argument is (fully) known.  Of course the results would depend on
> the implementation.  It would be interesting to compare the results if
> you used the optimize option (it's either -o or -O).
> 
> Bill

I don't think that optimisation can do much here, but there's another aspect 
that has a realistic chance to affect the result: 

None in values 

checks equality, and that may be slower than comparing identities:

$ python3 -m timeit -s"from slow_eq import A; values = 1, 2, A()" "any(v is 
None for v in values)"
1000000 loops, best of 3: 1.1 usec per loop
$ python3 -m timeit -s"from slow_eq import A; values = 1, 2, A()" "None in 
values"
10 loops, best of 3: 1 sec per loop

That's of course an extreme example that I wilfully constructed:

$ cat slow_eq.py 
import time

class A:
    def __eq__(self, other):
        time.sleep(1)
        return NotImplemented


>>> C:\usr\share\robin\pythonDoc>python -m timeit -s"values=(1,2,None)"
>>> "any(v is None for v in values)"
>>> 1000000 loops, best of 3: 0.62 usec per loop
>>>
>>> C:\usr\share\robin\pythonDoc>python -m timeit
>>> -s"values=(None,2,None)" "any(v is None for v in values)"
>>> 1000000 loops, best of 3: 0.504 usec per loop
>>>
>>> C:\usr\share\robin\pythonDoc>python -m timeit
>>> -s"values=(None,2,None)" "None in values"
>>> 10000000 loops, best of 3: 0.0309 usec per loop
>>>
>>> C:\usr\share\robin\pythonDoc>python -m timeit -s"values=(1,2,None)"
>>> "None in values"
>>> 10000000 loops, best of 3: 0.097 usec per loop
>>
>> it also seems a bit less obvious





More information about the Python-list mailing list