Simply print current function name

Python tip for debugging: how to dynamically print the current function name using sys._getframe() for better error tracking and code debugging during development.

Simply print current function name
Photo by Rubaitul Azad / Unsplash

Hi all,

When developing, I hate having to search in which portion of my code I am. For Tippy, I searched for a way to always display the function name in case of an error.

Hopefully, Python offers a simple (but curious) way to perform this.

Here is how to print your function name as a string in Python :

import sys
  def tutut():
  """
  Dum function displaying its name!
  """
  print sys._getframe().f_code.co_name

if name == 'main':
  tutut()

And here is the result

[airballman@ubuntu:~]$ python tutut.py
tutut

There it is !

You can also find this tip in my Programming Tips page, in the Python section.