1
def my_func():
    stuff
    return something

my_object.my_method(my_func)

I want my_func to be able to refer to my_object. Essentially like deferred self, which means "whatever object I am in, refer to that"

rafaelc
  • 57,686
  • 15
  • 58
  • 82
Jonny Shanahan
  • 351
  • 3
  • 13

2 Answers2

1

You could use the inspect module

import inspect

def my_func():
    stuff
    my_object = inspect.stack()[1][0].f_locals["self"]
    return something

However, I guess a simpler approach would be to pass the instance as argument, such as

def my_func():
    stuff
    return something

my_object.my_method(my_func, caller=my_object)
rafaelc
  • 57,686
  • 15
  • 58
  • 82
0

You want to make a callback.

And here is a usage of callback in a design pattern.

Community
  • 1
  • 1
Xxxo
  • 1,784
  • 1
  • 15
  • 24