tags:

views:

213

answers:

4

In other languages I can obtain the current frame via a reflection api to determine what variables are local to the scope that I an currently in.

Is there a way to do this in Python?

A: 

See the dir function.

sorry - not actually relevant to the frame, but still useful!

Martin Beckett
A: 

Like many things in Python, namespaces are directly accessible at run-time. Specifically, the local namespace is accessible via the built-in locals function, and the global (module level) namespace is accessible via the built-in globals function.

http://www.faqs.org/docs/diveintopython/dialect_locals.html

Kai
+5  A: 
import sys    
sys._getframe(number)

The number being 0 for the current frame and 1 for the frame up and so on up.

The best introduction I have found to frames in python is here

However, look at the inspect module as it does most common things you want to do with frames.

David Raznick
Do you mean sys._getframe(number). In the version of python I"m using I don't see the underscore between get and frame.
chollida
Actually was a typo, oops. But be warned it is a private function and all implementations of python (jython, iron python) do things slightly differently.
David Raznick
A: 

I use these little guys for debugging and logging:

import sys

def LINE( back = 0 ):
    return sys._getframe( back + 1 ).f_lineno
def FILE( back = 0 ):
   return sys._getframe( back + 1 ).f_code.co_filename
def FUNC( back = 0):
    return sys._getframe( back + 1 ).f_code.co_name
def WHERE( back = 0 ):
   frame = sys._getframe( back + 1 )
   return "%s/%s %s()" % ( os.path.basename( frame.f_code.co_filename ), 
                           frame.f_lineno, frame.f_code.co_name )
Kevin Little