[Tutor] "if clause" in list comprehensions.

Sander Sweers sander.sweers at gmail.com
Mon Oct 19 21:57:08 CEST 2009

2009/10/19 Alan Gauld <alan.gauld at btinternet.com>:
>> 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!

Indeed, I was and stand corrected.

>>> In order to use a list comprehension I created this function instead.
>>> def upperfy(item)
>>>   try:
>>>       item = item.upper()
>>>   except AttributeError:
>>>       pass
>>>   return item
>> I would move return item under the except and remove the pass, other
>> might disagree on this.
> I would :-)
> Doing that would result in None being returned for each successful
> conversion. The OPs code is correct (even if unnecessary)

I missed that the try: did not return anything. I was thinking more of
something like this.

def upperfy(item):
        return item
    except AttributeError:
        return item

Thanks for correcting me!


PS: Note to self, never reply in a hurry :-(

More information about the Tutor mailing list