0

I have this:

import concurrent.futures

and then in a class method:

 self.future = executor.submit(self.listen_for_messages)

using JavaScript, we'd have to bind the method to the object instance:

 self.future = executor.submit(self.listen_for_messages.bind(self))

do we need to do that in Python and if not why not?

DilbertFan
  • 113
  • 1
  • 1
  • 9

2 Answers2

3

You don't need anything like the bind call the Javascript code involves. Javascript method binding doesn't work like Python method binding.

In Javascript, when you do thing.method(stuff), formally, the thing.method expression resolves to what the standard calls a Reference, which carries both the function and the information that this should be thing. The information about what this should be is used when you do thing.method(stuff), but it's discarded if you pass thing.method as a callback or do pretty much anything else with it. The bind call is needed to preserve the information about this.

In Python, instead of the "Reference" stuff, thing.method resolves to a bound method object, which carries the information about self in the object itself. This information is not discarded, whether you call the method immediately, save it to a variable, pass it to another function as a callback, or do whatever else with it. Nothing like bind is needed.

user2357112
  • 260,549
  • 28
  • 431
  • 505
1

You're calling your method self.listen_for_messages, which means it's already an instance method, bound to self. No explicit binding is necessary here.

Just for reference though, you can bind an unbound method as shown here.

entropy
  • 840
  • 6
  • 16