Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving/Printing execution context

Tags:

python

EDIT: This question has been solved with help from apphacker and ConcernedOfTunbridgeWells. I have updated the code to reflect the solution I will be using.

I am currently writing a swarm intelligence simulator and looking to give the user an easy way to debug their algorithms. Among other outputs, I feel it would be beneficial to give the user a printout of the execution context at the beginning of each step in the algorithm.

The following code achieves what I was needing.

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 output of:

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

Thank you to apphacker and ConcernedOfTunbridgeWells who pointed me towards this answer

like image 951
Mike Hamer Avatar asked May 17 '26 20:05

Mike Hamer


2 Answers

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)
like image 183
Bjorn Avatar answered May 19 '26 10:05

Bjorn


You can use __locals__ to get the local execution context. See this stackoverflow posting for some discussion that may also be pertinent.

like image 27
ConcernedOfTunbridgeWells Avatar answered May 19 '26 08:05

ConcernedOfTunbridgeWells



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!