How to get a function name as a string in Python?

Today, we will see the two most used methods to get a function name as a string in Python.

Using __name__ to get a function name as a string in Python

For user-defined functions

def I_am_function():
    return 'nothing'
print(I_am_function.__name__)

Output:

I_am_function

For Class methods

class CopyAssignment(object):
    def my_method(self):
        pass
print(CopyAssignment.my_method.__name__)

Output:

my_method

For functions of modules

import time
print(time.time.__name__)

Output:

time

Using __qualname__ to get a function name as a string in Python

For user-defined functions

def I_am_function():
    return 'nothing'
print(I_am_function.__qualname__)

Output:

I_am_function

For Class methods

class CopyAssignment(object):
    def my_method(self):
        pass
print(CopyAssignment.my_method.__qualname__)

Output:

CopyAssignment.my_method

For functions of modules

import time
print(time.time.__qualname__)

Output:

time

You can find more discussion on How to get a function name as a string in Python?

Thank you for visiting our website.

Share:

Author: Harry

Hello friends, thanks for visiting my website. I am a Python programmer. I, with some other members, write blogs on this website based on Python and Programming. We are still in the growing phase that's why the website design is not so good and there are many other things that need to be corrected in this website but I hope all these things will happen someday. But, till then we will not stop ourselves from uploading more amazing articles. If you want to join us or have any queries, you can mail me at admin@copyassignment.com Thank you