Relying on the behaviour of empty container in conditional statements

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Wed Jul 12 04:26:20 EDT 2006


Steven D'Aprano schreef:
> If seq can be None as well as a sequence, doing a test "if len(seq) > 0"
> won't save you because len(None) will fail. You need an explicit test
> for seq being None:
> 
> if seq is not None and len(seq) > 0
> 
> Or even better:
> 
> if seq
> 
> which Just Works regardless of the type of seq.

Yes, true.

I agree that testing in a Boolean context works best in those cases. 
After a good night's sleep I remember why I felt uneasy doing it like 
that: I feel that 'if seq' should be synonym with 'if seq is not None', 
but I can't explain why. No rational reasons I think; it's probably just 
from being used to C and C++ where 'if (p)' in pointer contexts is used 
as synonym for 'if (p != NULL)'.

In general I don't have too many problems using Python idioms instead of 
C or C++ idioms, but apparently sometimes my years of experience in 
these languages sometimes show trough in Python. Luckily my BASIC habits 
have died out long ago.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven



More information about the Python-list mailing list