Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning values from callback(s) in Python

Tags:

python

I am currently looking at trying to use a callback in Python.

What I would like to do is return a value from the callback and then use this return value for conditional processing. So for example if the user enters "Y" I would like to print something to the console.

As I am new to Python the code below is as close as I can get currently but:

a) I am not sure if it is the Pythonic way of doing it

b) the correct way of doing it?

    class Observable:
        def subscribe(self,callback):
            self.callback = callback

        def fire(self):
            self.callback()

    class CallBackStuff:
        def doCallback(self):
            userInput = raw_input("Please enter Y or N?")
            return userInput

    if __name__ == '__main__':
        s = CallBackStuff()
        o = Observable()
        o.subscribe(s.doCallback)
        t = o.fire()
        print t
like image 785
11 revs Avatar asked Oct 18 '25 00:10

11 revs


2 Answers

The easiest way I can think of to do this in your code is to just store the input as a variable in the CallBackStuff object. Then after you've called the call-back function, you can just access the input data from the CallBackStuff instance. Example below.

class Observable:
    def subscribe(self,callback):
        self.callback = callback

    def fire(self):
        self.callback()

class CallBackStuff:
    storedInput = None # Class member to store the input
    def doCallback(self):
        self.storedInput = raw_input("Please enter Y or N?")

if __name__ == '__main__':
    s = CallBackStuff()
    o = Observable()
    o.subscribe(s.doCallback)
    o.fire()
    print s.storedInput # Print stored input from call-back object
like image 63
Andy Rimmer Avatar answered Oct 20 '25 13:10

Andy Rimmer


class Observable(object):
    def __call__(self, fun):
        return fun()


class Callback(object):
    def docallback(self):
        inp = raw_input()
        return inp

if __name__ == "__main__":
    print Observable()(Callback().docallback)
like image 43
Siva Cn Avatar answered Oct 20 '25 15:10

Siva Cn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!