0

I was trying to store reference to unbound method and noticed that it is being automatically bound. See example below. Is there more elegant way to store unbound method in the class without binding it?

def unbound_method():
    print("YEAH!")

class A:
    bound_method = unbound_method
    unbound_methods = [unbound_method]


a = A()
a.unbound_methods[0]()  # succeeds

a.bound_method()        # fails
# TypeError: unbound_method() takes 0 positional arguments but 1 was given

This is not a standard "do you know about @staticmethod?" question. What I'm trying to achieve is provide a way for children of the class provide another handler or certain situations. I do not control the unbound_method itself, it is provided from some library.

def unbound_method_a():
    print("YEAH!")

def unbound_method_b():
    print("WAY MORE YEAH!")

class A:
    bound_method = unbound_method_a

class B(A):
    bound_method = unbound_method_b

a = A()
a.bound_method() #fails
# print("YEAH!")
b = B()
b.bound_method() #fails
# print("WAY MORE YEAH!")

It can be achieved by wrapping the unbound method some dummy object like array, or in a bound method, just to drop self reference like this:

def unbound_method_a():
    print("YEAH!")

def unbound_method_b():
    print("WAY MORE YEAH!")

class A:
    def call_unbound_method(self):
        return unbound_method_a()

class B(A):
    def call_unbound_method(self):
        return unbound_method_b()

a = A()
a.call_unbound_method()
# print("YEAH!")
b = B()
b.call_unbound_method()
# print("WAY MORE YEAH!")
P. Šileikis
  • 724
  • 1
  • 12
  • 26
  • Possible duplicate of [Static methods in Python?](http://stackoverflow.com/questions/735975/static-methods-in-python) – Ilja Everilä May 11 '16 at 08:24
  • 1
    As to the details, [all functions are non-data descriptors which return bound or unbound methods depending whether they are invoked from an object or a class](https://docs.python.org/3/howto/descriptor.html#functions-and-methods). – Ilja Everilä May 11 '16 at 08:26

1 Answers1

0

Not as far as I know. Would it be so bad if you just replace

a.bound_method()

with

A.bound_method()

? I can't think of a situation in which the first one can't be replaced by the second one.

Matthias Schreiber
  • 2,347
  • 1
  • 13
  • 20