/Lib/lib2to3/fixes/fix_isinstance.py

http://unladen-swallow.googlecode.com/ · Python · 52 lines · 36 code · 7 blank · 9 comment · 11 complexity · 921a0f20d0a6e47b4b1291d37599bf09 MD5 · raw file

  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. PATTERN = """
  13. power<
  14. 'isinstance'
  15. trailer< '(' arglist< any ',' atom< '('
  16. args=testlist_gexp< any+ >
  17. ')' > > ')' >
  18. >
  19. """
  20. run_order = 6
  21. def transform(self, node, results):
  22. names_inserted = set()
  23. testlist = results["args"]
  24. args = testlist.children
  25. new_args = []
  26. iterator = enumerate(args)
  27. for idx, arg in iterator:
  28. if arg.type == token.NAME and arg.value in names_inserted:
  29. if idx < len(args) - 1 and args[idx + 1].type == token.COMMA:
  30. iterator.next()
  31. continue
  32. else:
  33. new_args.append(arg)
  34. if arg.type == token.NAME:
  35. names_inserted.add(arg.value)
  36. if new_args and new_args[-1].type == token.COMMA:
  37. del new_args[-1]
  38. if len(new_args) == 1:
  39. atom = testlist.parent
  40. new_args[0].set_prefix(atom.get_prefix())
  41. atom.replace(new_args[0])
  42. else:
  43. args[:] = new_args
  44. node.changed()