tags:

views:

58

answers:

2

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

+1  A: 

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)
apphacker
That works well thanks. Is there a way to embed this within another function? As there are other actions that occur at the end of each iteration and it would be nice to group them within a single function.I realise that the locals() could be passed into the function, however this is not optimal.
Mike Hamer
You could use a closure and a dictionary higher in scope that you update with values from a call to locals during each iteration, but if passing locals() into the function isn't optimal, I doubt a closure would be.
apphacker
+1  A: 

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

ConcernedOfTunbridgeWells
Thanks, the linked thread sounds quite similar to what I was hoping to accomplish. I'll investigate grabbing `__locals__` from the stack frames and edit my question to report on the findings. Thanks, Mike
Mike Hamer