2

Is there any way I can get all of the functions of a module so I can call them?

If I say:

m.py:

__all__ = ['Bark']
def Bark():
    print('Bark')

main.py:

import m
for f in m.__all__:
   print(m.f)

I get an AttributeError: module 'm' has no attribute 'f'.

How can I get it to print

function Bark at 0x000000?

Odoul
  • 23
  • 4

3 Answers3

4

Where you have a string containing the attribute name, use getattr to get the attribute:

print(getattr(m, f))
wjandrea
  • 28,235
  • 9
  • 60
  • 81
0
import m
for name in dir(m):
    item = getattr(m, name)
    print(f"{name} is {type(item)}")
    if isinstance(item, types.FunctionType):
        print(f"{name} is a function!")
        # can call function thusly:
        # item(args...)

Now, do you really want to know if the item is a function, or do you want to know if it's callable? Those are two different things. You can use isinstance(item, types.FunctionType) as shown above, but see How do I detect whether a Python variable is a function? for more information.

0

Try this, function_list return all name and function of an object as a dictionary.

from types import FunctionType

def function_list(module):
    return {key:value for key, value in module.__dict__.items()
                if type(value) == FunctionType}
Jason Yang
  • 11,284
  • 2
  • 9
  • 23