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
  • 52,436
  • 15
  • 51
  • 78
Jonny Shanahan
  • 303
  • 3
  • 10

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
  • 52,436
  • 15
  • 51
  • 78
0

You want to make a callback.

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

Community
  • 1
  • 1
Xxxo
  • 1,620
  • 1
  • 13
  • 24