How to Retrieve Method Names in Python?

Whether you’re debugging, logging, or working on introspection tasks, knowing how to extract a method’s name programmatically can be quite handy. This blog post will explore how to accomplish this in Python.

Method 1: Introspection

πŸ§‘β€πŸ’» Introspection in Python refers to the ability of a program to examine the type or properties of an object at runtime. The most straightforward approach to get the name of a method is by using the __name__ attribute. For example, obj.my_method.__name__ returns the string 'my_method'.

Every Python function and method has this special attribute that holds its name as a string. Here’s a simple example:

class MyClass:
    def my_method(self):
        pass

# Instantiate the class
obj = MyClass()

# Get the method name
method_name = obj.my_method.__name__
print(method_name)  # Output: 'my_method'

Method 2: Python ‘inspect’ Module

For more advanced introspection, Python’s inspect module is the go-to tool. It offers a wide range of functions to get detailed information about live objects, including methods.

To use inspect to get a method’s name, you can do the following:

import inspect

class MyClass:
    def my_method(self):
        pass

# Using inspect to get the method name
method_name = inspect.getmembers(MyClass, predicate=inspect.isfunction)

print(method_name)  
# Output: [('my_method', <function MyClass.my_method at 0x...>)]

This method not only retrieves the name but also provides the memory address, offering more insight into the method’s identity.

Practical Applications

  1. Debugging and Logging: Knowing the method name programmatically is useful in debugging and creating detailed logs.
  2. Dynamic Function Invocation: In advanced scenarios, you might want to invoke functions dynamically based on their names.
  3. Building Frameworks and Libraries: For developers building complex frameworks or libraries, introspection is key for flexibility and extensibility.

To keep learning coding and tech, feel free to join my free email newsletter by downloading these cheat sheets: πŸ‘‡