Any, All predicates (and vector operations for free)

Alex Martelli aleaxit at yahoo.com
Sun Feb 16 09:32:36 EST 2003


Christos TZOTZIOY Georgiou wrote:

> Hello, people
> 
> I have created a class that allows ANY and ALL predicates on iterables;
> it was easy to also allow vector operations (eg add something to every
> item on the list).
> 
> However, to define class methods 'en masse', the only way I finally
> found to do it was using the exec statement; 'setattr(klass,
> attribute_name, result)' didn't do its magic.

That's because the object you're calling "klass" here doesn't exist
yet at the time you're trying to "set its attributes" -- it's created
(by its metaclass) when the class body is _finished_.

> Can you suggest a better method?  Look at the 'exec' statement in the

This is exactly the kind of jobs that custom metaclasses do best.  In
this case, though, if you only want to define one special class with
these wrapped special methods, an alternative that's just as good would
be to have the wrapping-loop just AFTER the class body.

> class All definition to see what I mean.  Example usage is at the end of
> the code.
> 
> BTW, would you consider these as a worthy candidate for inclusion in the
> standard library?  Do you often need to check that some condition
> applies to all items of a sequence?  If yes, please suggest any changes

No to the first, yes to the second.  In the frequent case in which I
want to test if some property holds on every item of an iterable (and
your code only works on sequences, plus a few other special iterables
such as dicts, NOT on many other iterables such as files and generators,
because for example it relies on len(), and most iterables don't and
can't support that), almost invariably I much prefer to bail out as soon
as a non-compliant item is found, rather than having to operate on all
items willy-nilly.  I find such semantics generally more important than
the "neat-o" syntax afforded by operator overloading.  So, for example,
to check if all items in an iteable of numbers are evenly divisible by N:

def alldivisible(it, N):
    for x in it:
        if x%N != 0: return False
    else:
        return True

is almost invariably much more to my liking.  Matter of taste, no doubt,
but I wouldn't want the standard library to encourage different semantics.


Alex





More information about the Python-list mailing list