Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AddImportsVisitor may add imports after usage #1023

Closed
andrecsilva opened this issue Sep 22, 2023 · 0 comments
Closed

AddImportsVisitor may add imports after usage #1023

andrecsilva opened this issue Sep 22, 2023 · 0 comments

Comments

@andrecsilva
Copy link
Contributor

Consider the following, suppose the c() call was just added by another transformation/codemod:

c()
import a
from b import d

Trying to add a c import will result in it being added after the call:

In [1]: import libcst as cst

In [2]: from libcst.codemod.visitors import AddImportsVisitor

In [3]: from libcst.codemod.visitors._imports import ImportItem

In [4]: print(cst.parse_module("c()\nimport a\nfrom b import d").visit(AddImportsVisitor(cst.codemod.CodemodContext(), [ImportItem('c',None,None)])).code)
c()
import a
from b import d
import c

In [5]: print(cst.parse_module("c()\nimport a\nfrom b import d").visit(AddImportsVisitor(cst.codemod.CodemodContext(), [ImportItem('b','c',None)])).code)
c()
import a
from b import c, d

A possible fix for that is to change it so that imports are only added at the top of the file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant