On Mon, Oct 19, 2009 at 9:20 PM, Alan Gauld <alan.ga...@btinternet.com>wrote:
> > > "Sander Sweers" <sander.swe...@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
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor