Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python get current variables of the caller function

Tags:

python

dir

def foo():
    a = 1
    b = 2
    dir() # prints [a, b]
    bar(?) 

der bar(foo_pointer):
    print dir(foo_pointer) # should print [a,b]

I was trying to use bar(sys.modules[__name__].main), but that gives not [a,b], but ['__call__','__class__' ...] without a and b.

I actually want to safe that pointer to use later, so i can't just pass the [a,b].

like image 424
user2941564 Avatar asked Oct 31 '13 13:10

user2941564


1 Answers

Use the sys._getframe() function to get access to the calling frame. Frame objects have a f_locals attribute giving you access to the local variables of that frame:

import sys

def bar():
    caller = sys._getframe(1)
    print caller.f_locals
like image 141
Martijn Pieters Avatar answered Nov 06 '22 13:11

Martijn Pieters