/Lib/lib2to3/fixes/fix_renames.py

http://unladen-swallow.googlecode.com/ · Python · 69 lines · 35 code · 12 blank · 22 comment · 10 complexity · 52f66737c4206d8cfa77bbb07af4a056 MD5 · raw file

  1. """Fix incompatible renames
  2. Fixes:
  3. * sys.maxint -> sys.maxsize
  4. """
  5. # Author: Christian Heimes
  6. # based on Collin Winter's fix_import
  7. # Local imports
  8. from .. import fixer_base
  9. from ..fixer_util import Name, attr_chain
  10. MAPPING = {"sys": {"maxint" : "maxsize"},
  11. }
  12. LOOKUP = {}
  13. def alternates(members):
  14. return "(" + "|".join(map(repr, members)) + ")"
  15. def build_pattern():
  16. #bare = set()
  17. for module, replace in MAPPING.items():
  18. for old_attr, new_attr in replace.items():
  19. LOOKUP[(module, old_attr)] = new_attr
  20. #bare.add(module)
  21. #bare.add(old_attr)
  22. #yield """
  23. # import_name< 'import' (module=%r
  24. # | dotted_as_names< any* module=%r any* >) >
  25. # """ % (module, module)
  26. yield """
  27. import_from< 'from' module_name=%r 'import'
  28. ( attr_name=%r | import_as_name< attr_name=%r 'as' any >) >
  29. """ % (module, old_attr, old_attr)
  30. yield """
  31. power< module_name=%r trailer< '.' attr_name=%r > any* >
  32. """ % (module, old_attr)
  33. #yield """bare_name=%s""" % alternates(bare)
  34. class FixRenames(fixer_base.BaseFix):
  35. PATTERN = "|".join(build_pattern())
  36. order = "pre" # Pre-order tree traversal
  37. # Don't match the node if it's within another match
  38. def match(self, node):
  39. match = super(FixRenames, self).match
  40. results = match(node)
  41. if results:
  42. if any([match(obj) for obj in attr_chain(node, "parent")]):
  43. return False
  44. return results
  45. return False
  46. #def start_tree(self, tree, filename):
  47. # super(FixRenames, self).start_tree(tree, filename)
  48. # self.replace = {}
  49. def transform(self, node, results):
  50. mod_name = results.get("module_name")
  51. attr_name = results.get("attr_name")
  52. #bare_name = results.get("bare_name")
  53. #import_mod = results.get("module")
  54. if mod_name and attr_name:
  55. new_attr = LOOKUP[(mod_name.value, attr_name.value)]
  56. attr_name.replace(Name(new_attr, prefix=attr_name.get_prefix()))