1

I'd like to hold reference to callback functions in a singleton. However, python does some magic (either at the point of assignment or at the point of calling), that means the function requires an instance object as the first parameter -- I want to be able to store a simple function. How can I do this?

Assigning to X.__dict__ has the same effect.

def default(): print "default"

class X:
    func = None

    @staticmethod
    def setup(f=default):
        X.func = f

    @staticmethod
    def doit():
        if X.func is None: X.setup()
        # !!!!!!!
        # TypeError: unbound method g() must be called with X instance as first argument (got nothing instead)
        X.func()


def g(): print "g"
X.setup(g)
X.doit()
3
  • 3
    Why does X exist at all? Why did you define a class for this, especially if you're not going to make instances of the class? Commented Jan 25, 2018 at 18:47
  • 1
    Possible duplicate of storing unbound python functions in a class object Commented Jan 25, 2018 at 18:49
  • 2
    And why are you using an old-style class? More to the point, why are you using Python 2? Commented Jan 25, 2018 at 18:52

1 Answer 1

2

First,

If you do :

X.func() after X.setup(). It won't work. The problem is with the setup function.

The first problem is your f=default. This syntax does not work in python. You cannot assign a variable to a default parameter.

Concerning your problem itself, what happen is that your class X does not "bound" with function g (or default).

You need

def default(): print "default"

class X:
    func = None

    @staticmethod
    def setup(f):
        if f is None:
            X.func = staticmethod(default)
        else:
            X.func = staticmethod(f)

    @staticmethod
    def doit():
        if X.func is None: X.setup()
        X.func()

def g(): print "g"
X.setup(g)
X.doit()

edit: Use python 3 please

Sign up to request clarification or add additional context in comments.

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.