In Python, how do I obtain the current frame?

Question:

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?

Asked By: chollida

||

Answers:

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.

Answered By: David Raznick

I use these little guys for debugging and logging:

import os
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 )
Answered By: Kevin Little

The best answer would be to use the inspect module; not a private function in sys.

import inspect

current_frame = inspect.currentframe()
Answered By: notbad.jpeg
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.