3

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

user2672165
  • 2,986
  • 19
  • 27
Mike Hamer
  • 1,155
  • 11
  • 22
  • There is no need to tag the title since tags are officially supported. As much attention [Python] in the title might bring to your question, it doesn't measure up the big yellow background I get when you actually use 'python' as a tag. – Bjorn Apr 15 '09 at 08:10
  • Don't edit the question to say "solved" -- Accept the answer that solved it. Or post your own answer. – S.Lott Apr 15 '09 at 10:07
  • In future I will, however the edit simply replaced #???? with 2 lines that realised the function, so it was not a drastic change. – Mike Hamer Apr 15 '09 at 12:20

2 Answers2

1

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)
Bjorn
  • 69,215
  • 39
  • 136
  • 164
  • 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 Apr 15 '09 at 08:12
  • 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. – Bjorn Apr 15 '09 at 08:25
1

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

Community
  • 1
  • 1
ConcernedOfTunbridgeWells
  • 64,444
  • 15
  • 143
  • 197
  • 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 Apr 15 '09 at 08:18