How to list all functions in a Python module?

前端 未结 17 1714
野性不改
野性不改 2020-11-22 05:38

I have a python module installed on my system and I\'d like to be able to see what functions/classes/methods are available in it.

I want to call the doc function

相关标签:
17条回答
  • 2020-11-22 06:14

    For code that you do not wish to parse, I recommend the AST-based approach of @csl above.

    For everything else, the inspect module is correct:

    import inspect
    
    import <module_to_inspect> as module
    
    functions = inspect.getmembers(module, inspect.isfunction)
    

    This gives a list of 2-tuples in the form [(<name:str>, <value:function>), ...].

    The simple answer above is hinted at in various responses and comments, but not called out explicitly.

    0 讨论(0)
  • 2020-11-22 06:15

    None of these answers will work if you are unable to import said Python file without import errors. This was the case for me when I was inspecting a file which comes from a large code base with a lot of dependencies. The following will process the file as text and search for all method names that start with "def" and print them and their line numbers.

    import re
    pattern = re.compile("def (.*)\(")
    for i, line in enumerate(open('Example.py')):
      for match in re.finditer(pattern, line):
        print '%s: %s' % (i+1, match.groups()[0])
    
    0 讨论(0)
  • 2020-11-22 06:15

    The Python documentation provides the perfect solution for this which uses the built-in function dir.

    You can just use dir(module_name) and then it will return a list of the functions within that module.

    For example, dir(time) will return

    ['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'monotonic_ns', 'perf_counter', 'perf_counter_ns', 'process_time', 'process_time_ns', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'time_ns', 'timezone', 'tzname', 'tzset']

    which is the list of functions the 'time' module contains.

    0 讨论(0)
  • 2020-11-22 06:16

    Once you've imported the module, you can just do:

    help(modulename)
    

    ... To get the docs on all the functions at once, interactively. Or you can use:

    dir(modulename)
    

    ... To simply list the names of all the functions and variables defined in the module.

    0 讨论(0)
  • 2020-11-22 06:17

    You can use dir(module) to see all available methods/attributes. Also check out PyDocs.

    0 讨论(0)
  • 2020-11-22 06:19
    import sys
    from inspect import getmembers, isfunction
    fcn_list = [o[0] for o in getmembers(sys.modules[__name__], isfunction)]
    
    0 讨论(0)
提交回复
热议问题