To save a function's name as a string?

Asked 2 years ago, Updated 2 years ago, 54 views

Is there a way to save the name of a function as a string in a Python script? How do I implement get_functionion_name_as_string() in the source code below?

def my_function():
    pass

print get_functionion_name_as_string(my_function) #output: my_function

string python function

2022-09-22 11:05

1 Answers

class.__name__ is the name of the class or type. It can also be written in modules, classes, and built-in functions, so it can be written more widely than func_name.

import time
time.time.func_name #Error
time.time.__name__  #'time'

However, you can give warning in Python 3

sys._getframe([depth]) returns frame object from the stack top by depth on the call stack. If depth is greater than call stack, ValueError occurs.

import sys
this_function_name = sys._getframe().f_code.co_name


2022-09-22 11:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.