0

[An instance of object creation occurs when a reference to a bound method is created. This means that an ISR cannot pass a bound method to a function. One solution is to create a reference to the bound method in the class constructor and to pass that reference in the ISR. For example:][1]

class Foo():
    def __init__(self):
        self.bar_ref = self.bar  # Allocation occurs here
        self.x = 0.1
        tim = pyb.Timer(4)
        tim.init(freq=2)
        tim.callback(self.cb)

    def bar(self, _):
        self.x *= 1.2
        print(self.x)

    def cb(self, t):
        # Passing self.bar would cause allocation.
        micropython.schedule(self.bar_ref, 0)

Why does an allocation occur where the comment says it does?

Bob
  • 4,576
  • 7
  • 39
  • 107
  • Can you clarify exactly what you are asking? An allocation of what? A reference/pointer? An/the instance of Foo? Of the bound method? Something else? – Tom Dalton Jun 20 '18 at 15:51
  • I think it would good to mention that you're using [MicroPython](http://docs.micropython.org/en/latest/pyboard/index.html) – Peter Wood Jun 20 '18 at 15:51
  • 1
    The dotted attribute access `self.bar` is an invocation of descriptor `__get__`, creating a bound method. Details in the dupe answer (although the question is *entirely* different, the answer is the same). – wim Jun 20 '18 at 15:54
  • @wim where can I find documentation that `self.bar` invokes `__get__`? – Bob Jun 20 '18 at 16:44
  • [Here](https://docs.python.org/3/howto/descriptor.html#invoking-descriptors). – wim Jun 20 '18 at 17:15

0 Answers0