Favorite non-python language trick?

George Sakkis gsakkis at rutgers.edu
Sun Jun 26 09:25:04 EDT 2005


"Konstantin Veretennicov" <kveretennicov at gmail.com> wrote:

> > On 25 Jun 2005 12:17:20 -0700, George Sakkis <gsakkis at rutgers.edu> wrote:
> > If they go to itertools, they can simply be:
> >
> > def map(f, *iterables):
> >     return list(imap(f,*iterables))
> >
> > def filter(f, seq):
> >     return list(ifilter(f,seq))
>
> >>> from itertools import ifilter
> >>> def filter(f, seq):
> ...     return list(ifilter(f,seq))
> >>> filter(str.isalpha, 'not quite!')
> ['n', 'o', 't', 'q', 'u', 'i', 't', 'e']
> >>> __builtins__.filter(str.isalpha, 'not quite!')
> 'notquite'

Oops ! I've used filter only with lists and didn't know that it
preserves the type for strings and tuples. Here's a (hopefully) correct
version:

def filter(f,seq):
    it = ifilter(f,seq)
    if isinstance(seq,basestring):
        return ''.join(it)
    elif isinstance(seq,tuple):
        return tuple(it)
    else:
        return list(it)


By the way, the documentation of filter is unclear on what is the
return type if seq is a subclass of list, tuple, str, or unicode; is it
type(seq) or the base builtin type ? Let's see:

def subclassFactory(cls):
    return type("Dummy_" + cls.__name__, (cls,),
                {'__new__' : lambda self, seq: cls.__new__(self, seq)})

baseToSub = dict([(base,subclassFactory(base))
                 for base in list,tuple,str,unicode])

f = lambda x: x.lower()
for Base,Sub in baseToSub.iteritems():
    assert type(__builtins__.filter(f, Sub('lowerUPPERCap'))) is Base

for Base,Sub in baseToSub.iteritems():
    for cls in Base,Sub:
        args = (f, cls('lowerUPPERCap'))
        assert filter(*args) == __builtins__.filter(*args)


George




More information about the Python-list mailing list