/Lib/lib2to3/fixes/fix_types.py

http://unladen-swallow.googlecode.com/ · Python · 62 lines · 45 code · 1 blank · 16 comment · 0 complexity · 08728aeba77665139ce3f967cb24c2f1 MD5 · raw file

  1. # Copyright 2007 Google, Inc. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. """Fixer for removing uses of the types module.
  4. These work for only the known names in the types module. The forms above
  5. can include types. or not. ie, It is assumed the module is imported either as:
  6. import types
  7. from types import ... # either * or specific types
  8. The import statements are not modified.
  9. There should be another fixer that handles at least the following constants:
  10. type([]) -> list
  11. type(()) -> tuple
  12. type('') -> str
  13. """
  14. # Local imports
  15. from ..pgen2 import token
  16. from .. import fixer_base
  17. from ..fixer_util import Name
  18. _TYPE_MAPPING = {
  19. 'BooleanType' : 'bool',
  20. 'BufferType' : 'memoryview',
  21. 'ClassType' : 'type',
  22. 'ComplexType' : 'complex',
  23. 'DictType': 'dict',
  24. 'DictionaryType' : 'dict',
  25. 'EllipsisType' : 'type(Ellipsis)',
  26. #'FileType' : 'io.IOBase',
  27. 'FloatType': 'float',
  28. 'IntType': 'int',
  29. 'ListType': 'list',
  30. 'LongType': 'int',
  31. 'ObjectType' : 'object',
  32. 'NoneType': 'type(None)',
  33. 'NotImplementedType' : 'type(NotImplemented)',
  34. 'SliceType' : 'slice',
  35. 'StringType': 'bytes', # XXX ?
  36. 'StringTypes' : 'str', # XXX ?
  37. 'TupleType': 'tuple',
  38. 'TypeType' : 'type',
  39. 'UnicodeType': 'str',
  40. 'XRangeType' : 'range',
  41. }
  42. _pats = ["power< 'types' trailer< '.' name='%s' > >" % t for t in _TYPE_MAPPING]
  43. class FixTypes(fixer_base.BaseFix):
  44. PATTERN = '|'.join(_pats)
  45. def transform(self, node, results):
  46. new_value = _TYPE_MAPPING.get(results["name"].value)
  47. if new_value:
  48. return Name(new_value, prefix=node.get_prefix())
  49. return None