[Python-ideas] Predicate Sets

Daniel da Silva var.mail.daniel at gmail.com
Mon Jan 20 00:41:18 CET 2014


Below is a description of a very simple but immensely useful class called a
"predicate set". In combination with the set and list comprehensions they
would allow another natural layer of reasoning with mathematical set logic
in Python.

In my opinion, a concept like this would be best located in the functools
module.


*Overview:*
    Sets in mathematics can be defined by a list of elements without
repetitions, and alternatively by a predicate (function) that determines
inclusion. A predicate set would be a set-like class that is instantiated
with a predicate function that is called to determine ``a in
the_predicate_set''.

>> myset = predicateset(lambda s: s.startswith('a'))
>> 'xyz' in myset
False
>> 'abc' in myset
True
>> len(myself)
Traceback (most recent call last):
  [...]
TypeError

*Example Uses:*
# Dynamic excludes in searching
foo_files = search_files('foo', exclude=set(['a.out', 'Makefile']))
bar_files = search_files('bar', exclude=predicateset(lambda fname: not
fname.endswith('~'))) # exclude *~

# Use in place of a set with an ORM
validusernames = predicateset(lambda s: re.match(s, '[a-zA-Z0-9]+'))

class Users(db.Model):
    username = db.StringProperty(choices=validusernames)
    password = db.StringProperty()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140119/f7c7631e/attachment-0001.html>


More information about the Python-ideas mailing list