google / pasta

Library to refactor python code through AST manipulation.
Apache License 2.0
341 stars 40 forks source link

get_unused_import_aliases struggling with imports not at the top #32

Open akov opened 6 years ago

akov commented 6 years ago

I get an error when there's an unused import alias but its inside the code:

In [4]: import pasta

In [5]: src = """
   ...: def fun():
   ...:   import a_thing
   ...:   return 1
   ...: 
   ...: fun()
   ...: """

In [6]: tree = pasta.parse(src)

In [7]: from pasta.augment import import_utils

In [8]: import_utils.get_unused_import_aliases(tree)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-12-1eb7af7a6dac> in <module>()
----> 1 import_utils.get_unused_import_aliases(tree)

pasta/augment/import_utils.py in get_unused_import_aliases(tree, sc)
     76     if isinstance(node, ast.alias):
     77       name = sc.names[
---> 78           node.asname if node.asname is not None else node.name]
     79       if not name.reads:
     80         unused_aliases.add(node)

KeyError: 'a_thing'
soupytwist commented 6 years ago

This is because 'a_thing' is listed in scope.external_references but not in scope.names (because it's not in the root scope, it's in a sub-scope for the function). Need to do some rework of the result of external_references I think, it's not very useful right now for anything not imported globally.