In Python, functions are first-class citizens, which means they can be treated like any other object. This includes accessing their names as strings. In this tutorial, we will explore how to get a function’s name as a string using various methods.
Using the __name__
Attribute
The most straightforward way to get a function’s name is by accessing its __name__
attribute. This attribute returns the name of the function as a string.
def my_function():
pass
print(my_function.__name__) # Output: "my_function"
This method works uniformly for all types of functions, including built-in functions and methods.
Getting the Current Function’s Name
To get the current function’s name from inside it, you can use the inspect
module. Specifically, you can access the f_code.co_name
attribute of the current frame.
import inspect
def my_function():
this_function_name = inspect.currentframe().f_code.co_name
print(this_function_name) # Output: "my_function"
my_function()
Note that sys._getframe
also works instead of inspect.currentframe
, although the latter avoids accessing a private function.
Getting the Calling Function’s Name
If you want to get the calling function’s name instead, you can use the f_back
attribute of the current frame.
import inspect
def my_function():
this_function_name = inspect.currentframe().f_code.co_name
print(this_function_name) # Output: "my_function"
def caller_function():
my_function()
caller_function()
To get the calling function’s name, you can modify the code as follows:
import inspect
def my_function():
calling_function_name = inspect.currentframe().f_back.f_code.co_name
print(calling_function_name) # Output: "caller_function"
def caller_function():
my_function()
caller_function()
Using __qualname__
for Class Methods
In Python 3.3 and later, you can use the __qualname__
attribute to get the qualified name of a function or method.
class MyClass:
def my_method(self):
pass
print(MyClass.my_method.__name__) # Output: "my_method"
print(MyClass.my_method.__qualname__) # Output: "MyClass.my_method"
Best Practices and Tips
- Always use the
__name__
attribute to get a function’s name, as it is the most straightforward and uniform method. - Use the
inspect
module to get the current or calling function’s name when needed. - Be aware of the differences between
__name__
and__qualname__
attributes, especially when working with class methods.
By following these guidelines and using the provided code examples, you should be able to effectively work with function names as strings in Python.