578

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 help function on each one. In Ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in Python?

e.g. something like:

from somemodule import foo
print(foo.methods)  # or whatever is the correct method to call
martineau
  • 119,623
  • 25
  • 170
  • 301
Chris Gow
  • 7,514
  • 4
  • 23
  • 18

20 Answers20

616

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

camflan
  • 16,560
  • 3
  • 22
  • 19
  • 20
    This isn’t strictly true. The `dir()` function “attempts to produce the most relevant, rather than complete, information”. Source: http://docs.python.org/library/functions.html#dir . – Zearin Apr 17 '12 at 14:08
  • 16
    @jAckOdE Quoted? Then you'll get available methods and attributes of the string module. – OrangeTux May 06 '14 at 07:44
  • @OrangeTux: oops, that supposed to be a question. yeap, you answered it. – jAckOdE May 08 '14 at 07:34
  • 1
    The OP clearly asks for functions, not variables. Cf answers using `inspect`. – Jonathan H Mar 15 '18 at 16:13
  • Note that for the currently active module, you need to call dir without a parameter (which then can only list things defined until the point in time where dir is called, obviously) – PlasmaHH May 16 '22 at 09:37
278

Use the inspect module:

from inspect import getmembers, isfunction

from somemodule import foo
print(getmembers(foo, isfunction))

Also see the pydoc module, the help() function in the interactive interpreter and the pydoc command-line tool which generates the documentation you are after. You can just give them the class you wish to see the documentation of. They can also generate, for instance, HTML output and write it to disk.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Thomas Wouters
  • 130,178
  • 23
  • 148
  • 122
  • 4
    I've made the case for using the `ast` module in certain situations in [my answer](http://stackoverflow.com/a/31005891/21028). – csl Jun 23 '15 at 14:57
  • 63
    TL;DR of answers below: use [`dir`](https://stackoverflow.com/a/142501/472610) to return functions and variables; use [`inspect`](https://stackoverflow.com/a/46105518/472610) to filter functions only; and use [`ast`](https://stackoverflow.com/a/31005891/472610) to parse without importing. – Jonathan H Mar 20 '18 at 09:55
  • It's worth testing out each of the approaches as summarized by Sheljohn as the resulting output is drastically different from one solution to the next. – clozach Mar 31 '18 at 22:45
  • This does not appear to pull up functions that were dynamically added via `setattr` – Paul Richter Jan 17 '23 at 23:35
232

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.

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
Dan Lenski
  • 76,929
  • 13
  • 76
  • 124
  • 3
    @sheljohn… what's the point of this critique? My solution *also* lists functions, and the `inspect ` module can also list variables, even though not explicitly requested here. This solution requires only built-in objects, which can be very useful in some cases where Python is installed in a constrained/locked-down/broken environment. – Dan Lenski Mar 18 '18 at 20:16
  • Thanks, this almost worked, but I thought that `dir` would print the results, however it looks like you need to do `print(dir(modulename))`. – Eliot Sep 12 '19 at 05:31
  • 3
    This answer was definitely the most "help"ful. Thanks for sharing that tip! I now find help(modulename) to be my favorite. – TryTryAgain Apr 17 '21 at 18:55
  • @DanLenski Where exactly do you run these commands? I tried running them in the python shell, and in windows command prompt, and they didn't work. – user56202 Oct 31 '21 at 16:24
  • @user56202 I know this is close to a year old, but just incase anyone else is looking right. You can use IDLE, but in IDLE you need to import the module before using help so it's able to be accessed. – BobKayser Aug 01 '22 at 07:06
  • @BobKayser, in _any_ implementation of Python the symbol `modulename` needs to exist before you can do `help(modulename)`; there's nothing IDLE-specific about this. – Dan Lenski Oct 03 '22 at 17:20
133

Use inspect.getmembers to get all the variables/classes/functions etc. in a module, and pass in inspect.isfunction as the predicate to get just the functions:

from inspect import getmembers, isfunction
from my_project import my_module
    
functions_list = getmembers(my_module, isfunction)

getmembers returns a list of tuples (object_name, object) sorted alphabetically by name.

You can replace isfunction with any of the other isXXX functions in the inspect module.

Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117
adnan
  • 1,364
  • 1
  • 8
  • 3
  • 30
    `getmembers` can take a predicate, so your example could also be written: `functions_list = [o for o in getmembers(my_module, isfunction)]` – Christopher Currie Dec 04 '12 at 23:01
  • 35
    @ChristopherCurrie, you could also avoid the useless list comprehension with `functions_list = getmembers(my_module, predicate)` because it already returns a list ;) – Nil Feb 19 '14 at 21:43
  • 7
    To find if the function is defined in that module (rather than imported) add: to "if isfunction(o[1]) **and o[1].__module__ == my_module.__name__** " -- note it won't work necessarily if the imported function comes from a module with the same name as this module. – Michael Scott Asato Cuthbert Jan 11 '18 at 09:01
  • Is it possible to determine if the function is defined in my_module or is imported into my_module? – SMeznaric Jan 10 '22 at 11:53
75
import types
import yourmodule

print([getattr(yourmodule, a) for a in dir(yourmodule)
  if isinstance(getattr(yourmodule, a), types.FunctionType)])
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Oli
  • 15,345
  • 8
  • 30
  • 36
  • 8
    For this route, use getattr(yourmodule, a, None) instead of yourmodule.__dict__.get(a) – Thomas Wouters Sep 26 '08 at 12:53
  • 4
    your_module.__dict__ is my choice because you actually get a dict containing functionName: and you now have the ability to CALL that function dynamically. good times! – jsh Jan 28 '11 at 21:31
  • 1
    Python 3 friendly with some sugar: import types def print_module_functions(module): print('\n'.join([str(module.__dict__.get(a).__name__) for a in dir(module) if isinstance(module.__dict__.get(a), types.FunctionType)])) – y.selivonchyk Jul 10 '17 at 17:48
  • 1
    This will also list all functions that that module imports. That may or may not be what you want. – scubbo Jun 10 '20 at 20:27
66

For completeness' sake, I'd like to point out that sometimes you may want to parse code instead of importing it. An import will execute top-level expressions, and that could be a problem.

For example, I'm letting users select entry point functions for packages being made with zipapp. Using import and inspect risks running astray code, leading to crashes, help messages being printed out, GUI dialogs popping up and so on.

Instead I use the ast module to list all the top-level functions:

import ast
import sys

def top_level_functions(body):
    return (f for f in body if isinstance(f, ast.FunctionDef))

def parse_ast(filename):
    with open(filename, "rt") as file:
        return ast.parse(file.read(), filename=filename)

if __name__ == "__main__":
    for filename in sys.argv[1:]:
        print(filename)
        tree = parse_ast(filename)
        for func in top_level_functions(tree.body):
            print("  %s" % func.name)

Putting this code in list.py and using itself as input, I get:

$ python list.py list.py
list.py
  top_level_functions
  parse_ast

Of course, navigating an AST can be tricky sometimes, even for a relatively simple language like Python, because the AST is quite low-level. But if you have a simple and clear use case, it's both doable and safe.

Though, a downside is that you can't detect functions that are generated at runtime, like foo = lambda x,y: x*y.

csl
  • 10,937
  • 5
  • 57
  • 89
  • 4
    I like this; I'm currently trying to find out if someone has already written a tool that does something like pydoc but without importing the module. So far this is the best example i've found of this :) – James Mills Dec 14 '15 at 19:23
  • 1
    Agreed with this answer. I have need for this function to work regardless of what the target file may import or what version of python it is written for. This does not run into the import issues that imp and importlib do. – Eric Evans Jun 05 '19 at 18:57
  • How about module variables (`__version__` etc). Is there a way to get that? – Frak Apr 13 '20 at 18:06
49

For code that you do not wish to evaluate, I recommend an AST-based approach (like csl's answer), e.g.:

import ast

source = open(<filepath_to_parse>).read()
functions = [f.name for f in ast.parse(source).body
             if isinstance(f, ast.FunctionDef)]

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.

Cireo
  • 4,197
  • 1
  • 19
  • 24
27

This will do the trick:

dir(module) 

However, if you find it annoying to read the returned list, just use the following loop to get one name per line.

for i in dir(module): print i
X-Istence
  • 16,324
  • 6
  • 57
  • 74
Algorias
  • 3,043
  • 5
  • 22
  • 16
  • 2
    The OP clearly asks for functions, not variables. Cf answers using `inspect`. Besides, how this different from @DanLenski's answer? – Jonathan H Mar 15 '18 at 16:15
22

dir(module) is the standard way when using a script or the standard interpreter, as mentioned in most answers.

However with an interactive python shell like IPython you can use tab-completion to get an overview of all objects defined in the module. This is much more convenient, than using a script and print to see what is defined in the module.

  • module.<tab> will show you all objects defined in the module (functions, classes and so on)
  • module.ClassX.<tab> will show you the methods and attributes of a class
  • module.function_xy? or module.ClassX.method_xy? will show you the docstring of that function / method
  • module.function_x?? or module.SomeClass.method_xy?? will show you the source code of the function / method.
bmu
  • 35,119
  • 13
  • 91
  • 108
19

For global functions dir() is the command to use (as mentioned in most of these answers), however this lists both public functions and non-public functions together.

For example running:

>>> import re
>>> dir(re)

Returns functions/classes like:

'__all__', '_MAXCACHE', '_alphanum_bytes', '_alphanum_str', '_pattern_type', '_pickle', '_subx'

Some of which are not generally meant for general programming use (but by the module itself, except in the case of DunderAliases like __doc__, __file__ ect). For this reason it may not be useful to list them with the public ones (this is how Python knows what to get when using from module import *).

__all__ could be used to solve this problem, it returns a list of all the public functions and classes in a module (those that do not start with underscores - _). See Can someone explain __all__ in Python? for the use of __all__.

Here is an example:

>>> import re
>>> re.__all__
['match', 'fullmatch', 'search', 'sub', 'subn', 'split', 'findall', 'finditer', 'compile', 'purge', 'template', 'escape', 'error', 'A', 'I', 'L', 'M', 'S', 'X', 'U', 'ASCII', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL', 'VERBOSE', 'UNICODE']
>>>

All the functions and classes with underscores have been removed, leaving only those that are defined as public and can therefore be used via import *.

Note that __all__ is not always defined. If it is not included then an AttributeError is raised.

A case of this is with the ast module:

>>> import ast
>>> ast.__all__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'ast' has no attribute '__all__'
>>>
Xantium
  • 11,201
  • 10
  • 62
  • 89
7

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])
ckb
  • 6,933
  • 3
  • 15
  • 11
  • 4
    In this case it's much better to use the `ast` module. See [my answer](http://stackoverflow.com/a/31005891/21028) for an example. – csl Jun 23 '15 at 14:56
  • I think this is a valid method. Why a downvote when it does? – m3nda Oct 20 '15 at 03:30
6

Finding the names (and callable objects) in the current script __main__

I was trying to create a standalone python script that used only the standard library to find functions in the current file with the prefix task_ to create a minimal homebrewed version of what npm run provides.

TL;DR

If you are running a standalone script you want to run inspect.getmembers on the module which is defined in sys.modules['__main__']. Eg,

inspect.getmembers(sys.modules['__main__'], inspect.isfunction)

But I wanted to filter the list of methods by prefix and strip the prefix to create a lookup dictionary.

def _inspect_tasks():
    import inspect
    return { f[0].replace('task_', ''): f[1] 
        for f in inspect.getmembers(sys.modules['__main__'], inspect.isfunction)
        if f[0].startswith('task_')
    }

Example Output:

{
 'install': <function task_install at 0x105695940>,
 'dev': <function task_dev at 0x105695b80>,
 'test': <function task_test at 0x105695af0>
}

Longer Version

I wanted the names of the methods to define CLI task names without having to repeat myself.

./tasks.py

#!/usr/bin/env python3
import sys
from subprocess import run

def _inspect_tasks():
    import inspect
    return { f[0].replace('task_', ''): f[1] 
        for f in inspect.getmembers(sys.modules['__main__'], inspect.isfunction)
        if f[0].startswith('task_')
    }

def _cmd(command, args):
    return run(command.split(" ") + args)

def task_install(args):
    return _cmd("python3 -m pip install -r requirements.txt -r requirements-dev.txt --upgrade", args)

def task_test(args):
    return _cmd("python3 -m pytest", args)

def task_dev(args):
    return _cmd("uvicorn api.v1:app", args)

if __name__ == "__main__":
    tasks = _inspect_tasks()

    if len(sys.argv) >= 2 and sys.argv[1] in tasks.keys():
        tasks[sys.argv[1]](sys.argv[2:])
    else:
        print(f"Must provide a task from the following: {list(tasks.keys())}")

Example no arguments:

λ ./tasks.py
Must provide a task from the following: ['install', 'dev', 'test']

Example running test with extra arguments:

λ ./tasks.py test -qq
s.ssss.sF..Fs.sssFsss..ssssFssFs....s.s    

You get the point. As my projects get more and more involved, it's going to be easier to keep a script up to date than to keep the README up to date and I can abstract it down to just:

./tasks.py install
./tasks.py dev
./tasks.py test
./tasks.py publish
./tasks.py logs
Josh Peak
  • 5,898
  • 4
  • 40
  • 52
  • @muuvmuuv inside the `sys.modules['__main__']` all code that is already imported in the `__main__` script should be there. I just tried this using the `inspect.isclass` instead of `inspect.isfunction` and it worked for me. https://docs.python.org/3/library/inspect.html#inspect.isclass – Josh Peak Apr 09 '21 at 22:55
5

Use vars(module) then filter out anything that isn't a function using inspect.isfunction:

import inspect
import my_module

my_module_functions = [f for f in vars(my_module).values() if inspect.isfunction(f)]

The advantage of vars over dir or inspect.getmembers is that it returns the functions in the order they were defined instead of sorted alphabetically.

Also, this will include functions that are imported by my_module, if you want to filter those out to get only functions that are defined in my_module, see my question Get all defined functions in Python module.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
4
import sys
from inspect import getmembers, isfunction
fcn_list = [o[0] for o in getmembers(sys.modules[__name__], isfunction)]
eid
  • 537
  • 5
  • 12
3

You can use the following method to get list all the functions in your module from shell:

import module

module.*?
Vishal Lamba
  • 149
  • 9
3

Except dir(module) or help(module) mentioned in previous answers, you can also try:
- Open ipython
- import module_name
- type module_name, press tab. It'll open a small window with listing all functions in the python module.
It looks very neat.

Here is snippet listing all functions of hashlib module

(C:\Program Files\Anaconda2) C:\Users\lenovo>ipython
Python 2.7.12 |Anaconda 4.2.0 (64-bit)| (default, Jun 29 2016, 11:07:13) [MSC v.1500 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import hashlib

In [2]: hashlib.
             hashlib.algorithms            hashlib.new                   hashlib.sha256
             hashlib.algorithms_available  hashlib.pbkdf2_hmac           hashlib.sha384
             hashlib.algorithms_guaranteed hashlib.sha1                  hashlib.sha512
             hashlib.md5                   hashlib.sha224
2
r = globals()
sep = '\n'+100*'*'+'\n' # To make it clean to read.
for k in list(r.keys()):
    try:
        if str(type(r[k])).count('function'):
            print(sep+k + ' : \n' + str(r[k].__doc__))
    except Exception as e:
        print(e)

Output :

******************************************************************************************
GetNumberOfWordsInTextFile : 

    Calcule et retourne le nombre de mots d'un fichier texte
    :param path_: le chemin du fichier à analyser
    :return: le nombre de mots du fichier

******************************************************************************************

    write_in : 

        Ecrit les donnees (2nd arg) dans un fichier txt (path en 1st arg) en mode a,
        :param path_: le path du fichier texte
        :param data_: la liste des données à écrire ou un bloc texte directement
        :return: None


 ******************************************************************************************
    write_in_as_w : 

            Ecrit les donnees (2nd arg) dans un fichier txt (path en 1st arg) en mode w,
            :param path_: le path du fichier texte
            :param data_: la liste des données à écrire ou un bloc texte directement
            :return: None
2

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.

1

This will append all the functions that are defined in your_module in a list.

result=[]
for i in dir(your_module):
    if type(getattr(your_module, i)).__name__ == "function":
        result.append(getattr(your_module, i))
amine
  • 502
  • 5
  • 14
1

If you want to get the list of all the functions defined in the current file, you can do it that way:

# Get this script's name.
import os
script_name = os.path.basename(__file__).rstrip(".py")

# Import it from its path so that you can use it as a Python object.
import importlib.util
spec = importlib.util.spec_from_file_location(script_name, __file__)
x = importlib.util.module_from_spec(spec)
spec.loader.exec_module(x)

# List the functions defined in it.
from inspect import getmembers, isfunction
list_of_functions = getmembers(x, isfunction)

As an application example, I use that for calling all the functions defined in my unit testing scripts.

This is a combination of codes adapted from the answers of Thomas Wouters and adrian here, and from Sebastian Rittau on a different question.

Guimoute
  • 4,407
  • 3
  • 12
  • 28