4

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
3
  • 3
    why not just return self.callback() ? Commented Oct 25, 2013 at 9:24
  • @GamesBrainiac Related but no return value there I think Commented Oct 25, 2013 at 9:25
  • @BartoszKP You're right. Commented Oct 25, 2013 at 9:26

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

Comments

1
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.