facebook / usort

Safe, minimal import sorting for Python projects.
https://usort.readthedocs.io
MIT License
185 stars 22 forks source link

Sorting error with two shadow imports #308

Open amyreese opened 2 months ago

amyreese commented 2 months ago

Attempting to sort the following code:

from alpha.something import something
from beta import another
from beta import another
from alpha import something

Results in the following exception when sorting:

Error sorting foo.py: 'another'
Traceback (most recent call last):
  File "/Users/amethyst/workspace/usort/usort/api.py", line 33, in usort
    new_mod = sorter.sort_module()
              ^^^^^^^^^^^^^^^^^^^^
  File "/Users/amethyst/workspace/usort/usort/sorting.py", line 307, in sort_module
    new_module = self.wrapper.visit(self.transformer)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/amethyst/workspace/usort/.venv/lib/python3.12/site-packages/libcst/metadata/wrapper.py", line 204, in visit
    return self.module.visit(visitor)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/amethyst/workspace/usort/.venv/lib/python3.12/site-packages/libcst/_nodes/module.py", line 89, in visit
    result = super(Module, self).visit(visitor)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/amethyst/workspace/usort/.venv/lib/python3.12/site-packages/libcst/_nodes/base.py", line 236, in visit
    leave_result = visitor.on_leave(self, with_updated_children)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/amethyst/workspace/usort/.venv/lib/python3.12/site-packages/libcst/_visitors.py", line 71, in on_leave
    updated_node = leave_func(original_node, updated_node)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/amethyst/workspace/usort/usort/sorting.py", line 350, in leave_Module
    sorted_body = self.sorter.find_and_sort_blocks(
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/amethyst/workspace/usort/usort/sorting.py", line 280, in find_and_sort_blocks
    blocks = list(self.sortable_blocks(body))
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/amethyst/workspace/usort/usort/sorting.py", line 190, in sortable_blocks
    current = self.split_inplace(current, overlap)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/amethyst/workspace/usort/usort/sorting.py", line 167, in split_inplace
    new.imported_names[key] = block.imported_names.pop(key)
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
KeyError: 'another'