fix_isinstance.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # Copyright 2008 Armin Ronacher.
  2. # Licensed to PSF under a Contributor Agreement.
  3. """Fixer that cleans up a tuple argument to isinstance after the tokens
  4. in it were fixed. This is mainly used to remove double occurrences of
  5. tokens as a leftover of the long -> int / unicode -> str conversion.
  6. eg. isinstance(x, (int, long)) -> isinstance(x, (int, int))
  7. -> isinstance(x, int)
  8. """
  9. from .. import fixer_base
  10. from ..fixer_util import token
  11. class FixIsinstance(fixer_base.BaseFix):
  12. BM_compatible = True
  13. PATTERN = """
  14. power<
  15. 'isinstance'
  16. trailer< '(' arglist< any ',' atom< '('
  17. args=testlist_gexp< any+ >
  18. ')' > > ')' >
  19. >
  20. """
  21. run_order = 6
  22. def transform(self, node, results):
  23. names_inserted = set()
  24. testlist = results["args"]
  25. args = testlist.children
  26. new_args = []
  27. iterator = enumerate(args)
  28. for idx, arg in iterator:
  29. if arg.type == token.NAME and arg.value in names_inserted:
  30. if idx < len(args) - 1 and args[idx + 1].type == token.COMMA:
  31. next(iterator)
  32. continue
  33. else:
  34. new_args.append(arg)
  35. if arg.type == token.NAME:
  36. names_inserted.add(arg.value)
  37. if new_args and new_args[-1].type == token.COMMA:
  38. del new_args[-1]
  39. if len(new_args) == 1:
  40. atom = testlist.parent
  41. new_args[0].prefix = atom.prefix
  42. atom.replace(new_args[0])
  43. else:
  44. args[:] = new_args
  45. node.changed()