-1

I'm trying to do something really ugly and need help. From some method, I'm trying to analyze the stack and identify which class called this method as described here. But I want to go one step further and update some attribute of the instance of the class that called my method.

Example:

class A(object):
    self.a

    def some_func():
        analyze()

def analyze():
    frm = inspect.stack()[1]
    obj = find_obj_of_frm_by_magic(frm)
    obj.a = 1
Community
  • 1
  • 1
alnet
  • 1,093
  • 1
  • 12
  • 24

1 Answers1

1

I didn't use your "find_obj_of_frm_by_magic" method which I am assuming is the logic in that post you linked. I tried doing this instead, however I explicitly used the class and I was able to modify the instance doing the following.

I used the setattr method to add an attribute to the class. The only difference is that I am using the class explicitly.

class A(object):
    a = ""

    def some_func(self):
        analyze()

def analyze():
    frm = inspect.stack()[1]
    setattr(frm[0].f_globals.get('A'), 'stuff', 'boo')

a = A()
a.some_func()
# will output boo
print(a.stuff)
idjaw
  • 25,487
  • 7
  • 64
  • 83