Retrieving / Printing Execution Context

EDIT: This issue was resolved with apphacker and ConcernedOfTunbridgeWells. I updated the code to reflect the solution that I will use.

I am currently writing a swarm intelligence simulator and want to give the user a simple way to debug their algorithms. Among other results, I believe that it would be useful to provide the user with a listing of the execution context at the beginning of each step of the algorithm.

The following code accomplishes what I need.

import inspect

def print_current_execution_context():
    frame=inspect.currentframe().f_back #get caller frame
    print frame.f_locals #print locals of caller

class TheClass(object):
    def __init__(self,val):
        self.val=val
    def thefunction(self,a,b):
        c=a+b
        print_current_execution_context()


C=TheClass(2)
C.thefunction(1,2)

This gives the expected result:

{'a': 1, 'c': 3, 'b': 2, 'self': <__main__.TheClass object at 0xb7d2214c>}

Thanks to apfakker and ConcernedOfTunbridgeWells who pointed me to this answer

+3
source share
2 answers

to try:

class TheClass(object):
    def __init__(self,val):
        self.val=val
    def thefunction(self,a,b):
        c=a+b
        print locals()


C=TheClass(2)
C.thefunction(1,2)
+1
source

Source: https://habr.com/ru/post/1706439/