pyimport | | Cell 1 | Search

This code defines a module that provides a function called get_parameter_names, which takes a string of source code as input and returns a list of parameter names as strings. The function uses the ast module to parse the source code and extract the parameter names from the first function definition it finds.

Run example

npm run import -- "get python params"

get python params

import ast
# import inspect


def get_parameter_names(source):
    """
    Extracts parameter names from a function using the ast module.

    Args:
        func: The function to inspect.

    Returns:
        A list of parameter names as strings.
    """
    #source = inspect.getsource(func)
    tree = ast.parse(source)
    function_def = next((node for node in ast.walk(tree) if isinstance(node, ast.FunctionDef)), None)

    if function_def:
        return [function_def.name] + [arg.arg for arg in function_def.args.args]
    else:
        return []


__all__ = {
  "get_parameter_names": get_parameter_names,
}

What the code could have been:

import ast
import inspect


def extract_parameter_names(source_code: str) -> list[str]:
    """
    Extracts parameter names from a function using the ast module.

    Args:
        source_code (str): The source code of the function.

    Returns:
        list[str]: A list of parameter names as strings.
    """
    try:
        # Parse the source code into an abstract syntax tree
        tree = ast.parse(source_code)

        # Find the function definition in the abstract syntax tree
        function_def = next((node for node in ast.walk(tree) if isinstance(node, ast.FunctionDef)), None)

        # If the function definition exists, extract the parameter names
        if function_def:
            return [function_def.name] + [arg.arg for arg in function_def.args.args]
        # If the function definition does not exist, return an empty list
        else:
            return []

    except SyntaxError as e:
        # If a syntax error occurs, log the error message and return an empty list
        print(f"Syntax error: {e}")
        return []


def get_function_source_code(func, include_filename: bool = False) -> str:
    """
    Returns the source code of the given function.

    Args:
        func (callable): The function to get the source code from.
        include_filename (bool, optional): Whether to include the filename in the source code. Defaults to False.

    Returns:
        str: The source code of the function.
    """
    return inspect.getsource(func) if not include_filename else inspect.getsource(func).splitlines()[1]  # Remove the first line with the filename


__all__ = {
    "extract_parameter_names": extract_parameter_names,
    "get_function_source_code": get_function_source_code,
}

Code Breakdown

Import Statements

import ast
# import inspect

Function get_parameter_names

def get_parameter_names(source):
    """
    Extracts parameter names from a function using the ast module.

    Args:
        source: The source code of the function to inspect.

    Returns:
        A list of parameter names as strings.
    """
    #...

Function Implementation

tree = ast.parse(source)
function_def = next((node for node in ast.walk(tree) if isinstance(node, ast.FunctionDef)), None)
if function_def:
    return [function_def.name] + [arg.arg for arg in function_def.args.args]
else:
    return []

Module Exports

__all__ = {
  "get_parameter_names": get_parameter_names,
}