On Sat, Apr 25, 2009 at 4:01 PM, "Martin v. Löwis" <mar...@v.loewis.de> wrote: >> 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. > > Regards, > Martin >
Well in fact I would have written it like: def validate_commandline(rexes, line) : if not compare (rexes, line, re.match) : if len (rexes) != len (line) : raise ValueError ("mismatch len") mismatch = find_index (rexes, line, re.match, negate = True) raise ValueError ("mismatch at %d" % (mismatch)) Assuming, that I would have the function find_index. Ciprian. -- http://mail.python.org/mailman/listinfo/python-list