getgrit / gritql

GritQL is a query language for searching, linting, and modifying code.
https://docs.grit.io/
MIT License
3.17k stars 82 forks source link

add_import can insert the import in the wrong place resulting in invalid code #524

Closed eyurtsev closed 1 month ago

eyurtsev commented 1 month ago

Is there a way to specify where add_import should add the import?

The issue appears when imports in the global namespace aren't at the top of the file. This occurs very frequently in ipython notebooks, but at a relatively low frequency in non notebook code (e.g., if there's some logic that needs to check what to import before doing the import).

I don't expect that this will be encountered by python users outside of a notebook environment frequently, so not sure that this would be high value to fix for other users.

The issue appears when I run the following griql pattern:

Pattern

`TypedDict` as $X where {
      $X <: within `from typing import $_`,
      add_import(source="typing_extensions", name="TypedDict"),
      $X => .
}

Original code

from typing import TypedDict

def foo(x: TypedDict):
  pass

from typing_extensions import Annotated

def bar():
  pass

Resulting code (not valid python)

def foo(x: TypedDict):
  pass

from typing_extensions import Annotated, TypedDict

def meow():
  pass

Correct code


from typing_extensions import TypedDict

def foo(x: TypedDict):
  pass

from typing_extensions import Annotated

def bar():
  pass
eyurtsev commented 1 month ago

we can work around pretty easily by not using add_import , so also not urgent on our side

morgante commented 1 month ago

Thanks for the report, please update your stdlib and give the fix a try.