Lisp mentality vs. Python mentality

"Martin v. Löwis" martin at
Sat Apr 25 15:01:28 CEST 2009

>     Indeed the example I've given is purely theoretical. But still, I
> could find a use case for such a thing: just imagine we are building a
> small shell-like application that reads one line (the commands),
> splits it by spaces and always expects to have 4 elements and that
> each respects a given regular expression, one specific for each index.
> In this case I could syntactically check for correctness by doing
> this:
>     compare (regular_expressions, splitted_line, re.match)
>     Of course I could have just created a big regular expression for
> the entire line. But maybe my 4 elements come from variables obtained
> from a web-server query, or the regular expressions are not static but
> dynamically generated at run-time.

Ok, in this case I would write a function:

def validate_commandline(rexes, line):
    if len(rexes) != len(line):
        raise ValueError("Incorrect number of arguments, expected %d,"
                         "got %d" % (len(rexes), len(line)))
    for i in range(len(line)):
        if not re.match(rexes[i], line[i]):
            raise ValueError, "Incorrect argument %d" % i

IOW, in this specific case, I would not only want a true/false result,
but also an indication of the actual error to report to the user.
Your universal compare function would be no good here.


More information about the Python-list mailing list