[Tutor] "if clause" in list comprehensions.

ALAN GAULD alan.gauld at btinternet.com
Tue Oct 20 00:00:53 CEST 2009


Is there any compelling reason to write:
>
>[item.upper() for item in my_list if isinstance(item, basestring)]
>
>rather than the following?
>
>[item.upper() for item in my_list if hasattr(item, 'upper')]What happens if you have an object in your list that has 
an 'upper' merthod that, say, reboots your PC into an 
upper level of admin access? Or that sets the bank 
account credit limit to the upper limit?

Your list comprehension will happily run and apply upper 
to the object but the result may not be what you expected.
If you check isinstance you know that you are working with 
some kind of string at least. (A programmer could still 
override upper do do some wacky thing but then that 
programmer is abusing upper, whereas, in the bank account 
case it's a perfectly valid application of upper() )

Even more to the point the 'upper' that hasattr() finds may 
not be callable, it could be the upper value of a range for 
example. Then when you try to use it in the comprehension 
you will get an error.

Alan G.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091019/4282b5c3/attachment-0001.htm>


More information about the Tutor mailing list