Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep function namespace alive for debugging in IPython

In IPython, is there a way to import the namespace of a function into the interactive environment? For example, if I have a script, say, script.py:

def foo(x,y):
    z = x + y
    return z

a = 1
b = 2
c = foo(a,b)

and at the IPython prompt I write:

>> run script.py

Everything defined in script.py becomes a part of my environment, so if I write:

>> a

I'll get back 1.

What I want to do is to be able to dump the namespace of the function I call into my interpreter namespace so I can inspect the objects. Something like:

>> runfunction foo(1,2)
>> z

and get back that the value of z is 3.

I know about ipdb.set_trace(), and I could just add that to the end of my function to automatically enter the debugger, but I may not want to do this every time.

If this functionality doesn't exist, what is the recommended way to inspect the values of variables within a function for debugging purposes, though perhaps not every time I run it?

like image 200
jme Avatar asked Aug 12 '26 04:08

jme


1 Answers

You can use sys.settrace, here is an example, I save the locals dict to an attribute of the wrap function:

import sys

def get_locals(func):
    def wrap(*args, **kw):
        sys.settrace(tracefunc)
        try:
            res = func(*args, **kw)
        finally:
            sys.settrace(None)
        return res

    def tracefunc(frame, event, arg):
        if event == "return":
            if frame.f_code is func.func_code:
                wrap.last_res = frame.f_locals
        return tracefunc    

    return wrap

@get_locals
def foo(x,y):
    z = x + y
    return z

def bar(x, y):
    z = x - y
    return z

a = 1
b = 2
c = foo(a, b)
d = bar(a, b)

print foo.last_res

output:

{'y': 2, 'x': 1, 'z': 3}

If you want it be globals, you can update global dict with the locals dict.

like image 73
HYRY Avatar answered Aug 14 '26 18:08

HYRY



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!