Python tips — 4 one-liners to get the name of the calling function

Maria Bshara
2 min readOct 11, 2022

--

Debugging can be really hard for juniors who often struggle with the understanding of data flow and function calls. For example when we are talking about signals or form/formset save (talking about Django). Here are several simple solutions that will help you to nail it.

import sys
sys._getframe().f_back.f_code.co_name

It works fast, but it is an internal private function (given its leading underscore), therefore it's not recommended to use. Try not to use it anywhere but for debugging and definitely don’t let it go to the production.

import inspect
inspect.stack()[1][3]

The shortest way, it provides the info we need and is easy to remember/write but it is relatively slow.

import inspect
inspect.getouterframes(inspect.currentframe(), 2)[1][3]

A bit complicated, yet more appropriate than the previous ones. But what is [1][3]? We need to dive into the inspect module documentation to understand it (since it’s never a good idea to copy-paste code that you don’t understand)…

import inspect
inspect.currentframe().f_back.f_code.co_name

And finally, the solution that is understandable, fast, and doesn’t call private functions. Perfect!

--

--

Maria Bshara
Maria Bshara

Written by Maria Bshara

Backend Tech lead, Python engineer. Interested in AI and related topics 👾 Mostly writing about refactoring and python best practices :)

No responses yet