type_hintsยถ

Type Hints Transformer Module.

This module provides functionality to add type hints to function parameters and return types in Python code using LibCST. It allows for automated type annotation of existing code to improve type safety and code documentation.

Example

>>> import libcst as cst
>>> from haive.tools.toolkits.dev.python.cst_toolkit.transformers.type_hints import TypeHintTransformer
>>>
>>> # Read and parse source code
>>> with open("script.py", "f") as f:
>>>     tree = cst.parse_module(f.read())
>>>
>>> # Define type mapping
>>> type_map = {
>>>     "name": "str",
>>>     "age": "int",
>>>     "return": "bool"
>>> }
>>>
>>> # Apply type hints
>>> modified_tree = tree.visit(TypeHintTransformer(type_map))
>>>
>>> # Write updated code back to file
>>> with open("script.py", "w") as f:
>>>     f.write(modified_tree.code)

Classesยถ

TypeHintTransformer

Adds type hints to function parameters and return types.

Module Contentsยถ

class type_hints.TypeHintTransformer(type_map)ยถ

Bases: libcst.CSTTransformer

Adds type hints to function parameters and return types.

This transformer identifies function parameters and adds appropriate type annotations based on a provided mapping. It can also add a return type annotation to functions.

type_mapยถ

A dictionary mapping parameter names and โ€˜returnโ€™ to their types

Type:

dict

leave_FunctionDef(original_node, updated_node)ยถ

Add type hints to function definitions during the AST traversal.

This method adds type annotations to function parameters and return types based on the provided type_map.

Parameters:
  • original_node (cst.FunctionDef) โ€“ The original function definition node

  • updated_node (cst.FunctionDef) โ€“ The updated function definition node

Returns:

The function definition with added type hints for parameters

and return type if specified in the type_map

Return type:

cst.FunctionDef

type_mapยถ