The Import API
The Import API provides tools for working with imports and managing dependencies between files.
Accessing Imports
You can access these through File.imports and File.import_statements:
Common Operations
The Import API provides several methods for modifying imports:
Import Resolution
Imports can be traced to their original symbols:
Working with External Modules
You can determine if an import references an ExternalModule by checking the type of Import.imported_symbol, like so:
Bulk Operations
Here are patterns for working with multiple imports:
Always check if imports resolve to external modules before modification to avoid breaking third-party package imports.
Import Statements vs Imports
Codegen provides two levels of abstraction for working with imports:
- ImportStatement - Represents a complete import statement
- Import - Represents individual imported symbols
You can access these through File.imports and File.import_statements:
ImportStatement inherits from Statement, providing operations like remove()
and insert_before()
.