Codegen builds a complete dependency graph of your codebase, connecting functions, classes, imports, and their relationships. This enables powerful type resolution capabilities:
Copy
Ask AI
from codegen import Codebase# Initialize codebase with dependency graphcodebase = Codebase("./")# Get a function with a type annotationfunction = codebase.get_file("path/to/file.py").get_function("my_func")# Resolve its return type to actual symbolsreturn_type = function.return_typeresolved_symbols = return_type.resolved_types # Returns the actual Symbol objects# For generic types, you can resolve parametersif hasattr(return_type, "parameters"): for param in return_type.parameters: resolved_param = param.resolved_types # Get the actual type parameter symbols# For assignments, resolve their typeassignment = codebase.get_file("path/to/file.py").get_assignment("my_var")resolved_type = assignment.type.resolved_types
Type resolution follows imports and handles complex cases like type aliases, forward references, and generic type parameters.
for param in function.parameters: # Get parameter type param_type = param.type # -> TypeAnnotation print(param_type.source) # "int" print(param_type.is_typed) # True/False # Set parameter type param.set_type("int") param.set_type(None) # Removes type annotation
# For global/local assignmentsassignment = file.get_assignment("my_var")var_type = assignment.type # -> TypeAnnotationprint(var_type.source) # "str"# Set variable typeassignment.set_type("str")assignment.set_type(None) # Removes type annotation# For class attributesclass_def = file.get_class("MyClass")for attr in class_def.attributes: # Each attribute has an assignment property attr_type = attr.assignment.type # -> TypeAnnotation print(f"{attr.name}: {attr_type.source}") # e.g. "x: int" # Set attribute type attr.assignment.set_type("int")# You can also access attributes directly by indexfirst_attr = class_def.attributes[0]first_attr.assignment.set_type("str")
Union types (UnionType) can be manipulated as collections:
Copy
Ask AI
# Get union typeunion_type = function.return_type # -> A | B print(union_type.symbols) # ["A", "B"]# Add/remove optionsunion_type.append("float")union_type.remove("None")# Check contentsif "str" in union_type.options: print("String is a possible type")
Type resolution uses Type.resolved_value to get the actual symbols that a type refers to:
Copy
Ask AI
# Get the actual symbols for a typetype_annotation = function.return_type # -> Typeresolved_types = type_annotation.resolved_value # Returns an Expression, likely a Symbol or collection of Symbols# For generic types, resolve each parameterif hasattr(type_annotation, "parameters"): for param in type_annotation.parameters: param_types = param.resolved_value # Get symbols for each parameter# For union types, resolve each optionif hasattr(type_annotation, "options"): for option in type_annotation.options: option_types = option.resolved_value # Get symbols for each union option