Instagram / LibCST

A concrete syntax tree parser and serializer library for Python that preserves many aspects of Python's abstract syntax tree
https://libcst.readthedocs.io/
Other
1.57k stars 192 forks source link

`AddImportsVisitor`: Add the ability to import in an `if TYPE_CHECKING` block #1052

Open Viicos opened 1 year ago

Viicos commented 1 year ago

When using libcst to add types, we often want to add imports in a conditional if TYPE_CHECKING block, to avoid circular imports or improve performance.

It would be great to have an extra if_type_checking: bool parameter to AddImportsVisitor, that would add the import in the block (and import TYPE_CHECKING from typing if it is not already the case).

If you think this is a good idea, I may work on this.

Viicos commented 1 year ago

https://github.com/Instagram/MonkeyType/blob/49fc029acd3d31d3b5a68a89c3833dd90f18da0e/monkeytype/type_checking_imports_transformer.py#L29 Might be useful, will take a look

ankit-gautam23 commented 10 months ago

@Viicos I think adding this to monkeytype/type_checking_imports_transformer.py could solve your problem

@staticmethod def _add_type_checking_import(source_module: Module, if_type_checking: bool = False) -> Module: context = CodemodContext() transformer = MyAddImportsVisitor(context, if_type_checking) transformed_source_module = transformer.transform_module(source_module) return transformed_source_module