python get function name as string code example

Example 1: give a function a name python

def my_function():
    pass

class MyClass(object):
    def method(self):
        pass

print(my_function.__name__)         # gives "my_function"
print(MyClass.method.__name__)      # gives "method"

print(my_function.__qualname__)     # gives "my_function"
print(MyClass.method.__qualname__)  # gives "MyClass.method"

Example 2: give a function a name python

for i in a:
    print i.__name__

Example 3: python get function from string name

module = __import__('foo')
func = getattr(module, 'bar')
func()