Python | How to get function name?

Python | How to get function name?

In Python, if you want to retrieve the name of a function (either from within the function or outside it), you can use a combination of built-in libraries and attributes. Here's how you can achieve this:

  1. From Within the Function Using the inspect Module:

    This method allows you to retrieve the name of the current function from within the function itself.

    import inspect def my_function(): current_function_name = inspect.currentframe().f_globals['__name__'] print(current_function_name) my_function() # Output: __main__ 

    However, the above approach gives you the name of the module (__main__ in this case). To specifically get the function name:

    import inspect def my_function(): current_function_name = inspect.currentframe().f_code.co_name print(current_function_name) my_function() # Output: my_function 
  2. From Outside the Function Using the function Object:

    Every function in Python has a __name__ attribute that stores its name. You can access this attribute directly if you have a reference to the function.

    def another_function(): pass print(another_function.__name__) # Output: another_function 

The second method (using the __name__ attribute) is more straightforward and is typically used when you have a reference to the function and want to know its name. The first method (using the inspect module) is useful when you're inside a function and want to programmatically determine its name.


More Tags

memory-management node-gyp version-control clojurescript asp.net-mvc-3-areas salesforce-lightning flutter-appbar windows-server-2012 appearance message-queue

More Programming Guides

Other Guides

More Programming Examples