[Tutor] "if clause" in list comprehensions.

Emmanuel Ruellan emmanuel.ruellan at laposte.net
Mon Oct 19 22:36:05 CEST 2009


On Mon, Oct 19, 2009 at 9:20 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

>
>
> "Sander Sweers" <sander.sweers at gmail.com> wrote
>
>  mylist = ['John', 'Canada', 25, 32, 'right']
>>> a = [item.upper() for item in mylist if type(item) == type('good')]
>>>
>>
>> Usually it is recommended to use hasattr() instead of type()
>>   hasattr(s, 'upper')
>>
>
> Nope, they do  completely different things
> I think you might be thinking of isinstance() which can be used instead of
> type(). I see you use hasattr as a means of testing for a method but that is
> still different from testing type - the method names might be the same but
> the functions be completely different in effect!


When I read Sander's advice, I thought it would be the sensible thing to do
when working with strings that could be either vanilla 8-bit strings or
Unicode strings.

For example:
>>> my_list = ['a string', u'another string', 42]
>>> print [item.upper() for item in my_list if hasattr(item, 'upper')]
['A STRING', u'ANOTHER STRING']
>>> print [item.upper() for item in my_list if type(item) == type('good')]
['A STRING']

Thinking of it, the same result could be achieved with 'if isinstance(item,
basestring)'.

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')]


Emmanuel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091019/e416e77e/attachment.htm>


More information about the Tutor mailing list