Problem with Lexical Scope

jslowery at gmail.com jslowery at gmail.com
Thu Dec 15 21:45:17 EST 2005


Well, the the comparison operations are just a special case really.I
don't know about the obfuscation contest. I've attempted to make an
extensible library.

def lt(*fields):
    return collect(fields, lambda x, y: x < y)

def gt(*fields):
    return collect(fields, lambda x, y: x > y)

def gte(*fields):
    """ gte(field, ...) -> rule
    """
    return collect(fields, lambda x, y: x >= y)

etc...

The purpose of writing the collect function was just to be able to
easily apply the logic to whatever function was wanted.

the added ability is to be able to take as many arguments as it wants.

hire_rule = lt('birth_date', 'hire_date', 'fire_date')
cube_rule = eq('height', 'width', 'depth')

The reason that it's written like this is because I'm attempting to
make things as declarative as possible. I could use classes and
override __special__ operators and things like that but just applying
rules using prefix notation seems to work alright.

I've basically got a simple call signature...takes dict returns bool
that plugs into the little validation routine.

It turns out that envoking the rules is easistly expressed with a
closure, though I might switch to types if it needs that added
complexity.

But your assumption is correct, it's for dictionaries of data to be
validated. I haven't decided if I want to take advantage of the dict's
mutability to include formating as well.

Here's a bit from my unit test.

rule = when(all(have('length'), have('width')),
                   check(['length', 'width'], lambda x, y: x == y))
assert rule({'length' : '2', 'width' : '2'}) == True
assert rule({'length' : '2', 'width' : '1'}) == False
assert rule({'length' : '1', 'width' : '2'}) == False

I've also got a "collectable" equality function so that can be shown
as.

box_rule = when(all(have('length'), have('width')), eq('length',
'width'))

Which basically means, if we have both a length and a width, then be
sure they are equal.

Of course, there is a little function that performs a conjunction of a
complete list of rules on a dict and returns the rules that failed.

I've also got a little adapter that translates functions that take a
string and returns bool into one that fits the call signature called
match.

match(is_ssn, 'social-security_number')

Like I said, it may be considered more readable if using operator
overloading so that it uses python's native syntax. Considering the
added complexity, I don't know if it would be worth it. I'd probably
put a simple little declarative language on top of it to translate the
function calls before that.




More information about the Python-list mailing list