How to list all functions in a Python module?

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

    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.

提交回复
热议问题