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
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.
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])
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.
Once you've import
ed 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.
You can use dir(module)
to see all available methods/attributes. Also check out PyDocs.
import sys
from inspect import getmembers, isfunction
fcn_list = [o[0] for o in getmembers(sys.modules[__name__], isfunction)]