In Python, how do I obtain the current frame?
Asked Answered
B

3

38

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?

Brimmer answered 16/7, 2009 at 20:45 Comment(2)
The first Google result for "python inspect stack frame" returns the answer you want; docs.python.org/library/inspect.htmlCutcherry
note that u can use locals() to obtain local varsCamass
G
46
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.

Gianna answered 16/7, 2009 at 20:52 Comment(0)
R
43

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

import inspect

current_frame = inspect.currentframe()
Rhodos answered 11/5, 2013 at 22:23 Comment(2)
Thanks. But one thing to note, from that link: "CPython implementation detail: This function relies on Python stack frame support in the interpreter, which isn’t guaranteed to exist in all implementations of Python. If running in an implementation without Python stack frame support this function returns None."Huff
The inspect.currentframe() implementation actually calls the "private method in sys": sys._getframe(1) if hasattr(sys, "_getframe") else None. See line 1536 on the cpython codebase. This also means that even calling sys might not do the trick.Guttural
P
26

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 )
Poplin answered 16/7, 2009 at 21:46 Comment(2)
Is it possible to obtains frame's full path ?Churning
This might have been nice back in 2009, but users should just use stdlib inspect these days.Nonfiction

© 2022 - 2024 — McMap. All rights reserved.