AlokThakur AlokThakur - 4 months ago 11
Python Question

Pythonic way to Call a function with set of arguments until it return any thing but None

I know to use for loop and call my function till I get not None as return value, But I am looking for some python built in which can help here.

e.g. -

iter(myfunc(), None)
It will call
myfunc()
until it return
None


I am looking to code exactly opposite to this e.g. -
iter(myfunc(), not None), Call myfunc()
until it returns any thing but
None


Thanks in advance..

Answer

This answer is a bit of an exercise in the power of Python. I just get frustrated that iters 2-arity form doesn't take a function for its second parameter.

But it does, if you're crazy enough. See, you can redefine equality on an object, like so:

class Something:
    def __eq__(self, other):
        self.lastother = other
        return other is not None

sentinel = Something()
myiter = iter(myfunc, sentinel)
for nope in myiter:
    pass
match = sentinel.lastother

There. Enjoy. Python's pretty amazing that you can subvert the definition of equality this way. Have fun storming the castle!