How to list all functions in a Python module?

前端 未结 17 1715
野性不改
野性不改 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:09

    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 "", line 1, in 
    AttributeError: module 'ast' has no attribute '__all__'
    >>>
    

提交回复
热议问题