Basically, your solution is almost as elegant as it turns out (you could, of course, put it in the service module if you find it generally useful). You could if you wanted it to use the infinity object to shorten the code a bit, but then you should also include a class definition that extends the code again (if you haven't entered a class definition):
def checkSorted(it): prev = type("", (), {"__lt__": lambda a, b: False})() for x in it: if prev < x: raise ValueError("Not sorted") prev = x yield x
The first line uses type to create the class first and then instantiate it. Objects of this class are compared less than anything (an infinity object).
The problem with executing a single-line interface is that you need to deal with three constructs: you need to update the state (assignment), throw an exception, and execute a loop. You can easily execute them with statements, but including them in oneliner will mean that you have to try to put the instructions on one line, which in turn will cause a problem with the loop and if -constructs.
If you want to put all this into an expression, you will have to use dirty tricks for this, it can be the assignment and cyclization of iterutils , and throwing can be done using the throw method in the generator (which can also be represented in the expression):
imap( lambda i, j: (i >= j and j or (_ for _ in ()).throw(ValueError("Not sorted"))), *(lambda pre, it: (chain([type("", (), {"__ge__": lambda a, b: True})()], pre), it))(*tee(it)))
The last it is the iterator you want to test, and the expression is evaluated by a validated iterator. I agree that it doesnโt look good and itโs not obvious what he is doing, but you asked for it (and I donโt think you wanted it).