This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: ast.FunctionDef cannot find functions under if statement
Type: enhancement Stage: resolved
Components: Parser Versions: Python 3.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: JelleZijlstra, Ruishi, lys.nikolaou, pablogsal
Priority: normal Keywords:

Created on 2022-03-11 03:08 by Ruishi, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (4)
msg414886 - (view) Author: Ruishi (Ruishi) Date: 2022-03-11 03:08
When I use the Python ast package to get the functions of Python files, I find the functions defined in the body of `if` statement cannot be recognized.

Here is my code:
with open(py_file, 'r') as f:
    data = f.read()
    module = ast.parse(data)
    func_def = [node for node in module.body if isinstance(node, ast.FunctionDef)]

Here is an example of Python file:
if supports_bytes_environ:
    def _check_bytes(value):
        if not isinstance(value, bytes):
            raise TypeError("bytes expected, not %s" % type(value).__name__)
        return value

The function `_check_bytes` is not in `func_def`. I also tested `ast.iter_child_nodes(module)` and it also has this issue.
msg414887 - (view) Author: Ruishi (Ruishi) Date: 2022-03-11 03:11
I'm not sure whether I should file this issue here or on Github and I'm not an expert on this so I think I cannot contribute to this but only report to you.
msg414888 - (view) Author: Jelle Zijlstra (JelleZijlstra) * (Python committer) Date: 2022-03-11 04:09
This is the right place to file an issue.

Your code is incorrect; it will find only top-level functions. Functions within an `if` statement will be nested inside an `ast.If` node. To find all functions in a file, you'll need to recurse into nested nodes. For example, you could use `ast.walk`, an `ast.NodeVisitor`, or manually check for nodes like `ast.If`. Which one is best depends on your needs. For example, the first two will also find methods in classes. The ast module documentation has more information.
msg414891 - (view) Author: Ruishi (Ruishi) Date: 2022-03-11 07:01
I see. It's my misunderstanding. Thank you for your help!
History
Date User Action Args
2022-04-11 14:59:57adminsetgithub: 91136
2022-03-11 07:01:38Ruishisetmessages: + msg414891
2022-03-11 04:09:18JelleZijlstrasetstatus: open -> closed

nosy: + JelleZijlstra
messages: + msg414888

resolution: not a bug
stage: resolved
2022-03-11 03:11:24Ruishisetmessages: + msg414887
2022-03-11 03:08:56Ruishicreate