cpython/Lib/lib2to3/fixes/fix_itertools_imports.py
Martin v. Löwis c0098595db Merged revisions 77898 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk

................
  r77898 | martin.v.loewis | 2010-02-01 02:15:39 +0100 (Mo, 01 Feb 2010) | 17 lines

  Merged revisions 77855-77856,77870 via svnmerge from
  svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3

  ........
    r77855 | benjamin.peterson | 2010-01-30 17:32:05 +0100 (Sa, 30 Jan 2010) | 1 line

    don't return node if it is not changed
  ........
    r77856 | benjamin.peterson | 2010-01-30 17:35:29 +0100 (Sa, 30 Jan 2010) | 1 line

    return None to indicate no change
  ........
    r77870 | benjamin.peterson | 2010-01-31 02:21:26 +0100 (So, 31 Jan 2010) | 1 line

    never return the original node given to transform()
  ........
................
2010-02-01 01:17:43 +00:00

45 lines
1.6 KiB
Python

""" Fixer for imports of itertools.(imap|ifilter|izip|ifilterfalse) """
# Local imports
from .. import fixer_base
from ..fixer_util import BlankLine
class FixItertoolsImports(fixer_base.BaseFix):
PATTERN = """
import_from< 'from' 'itertools' 'import' imports=any >
""" %(locals())
def transform(self, node, results):
imports = results['imports']
children = imports.children[:] or [imports]
for child in children:
if not hasattr(child, 'value'):
# Handle 'import ... as ...'
continue
if child.value in ('imap', 'izip', 'ifilter'):
# The value must be set to none in case child == import,
# so that the test for empty imports will work out
child.value = None
child.remove()
elif child.value == 'ifilterfalse':
node.changed()
child.value = 'filterfalse'
# Make sure the import statement is still sane
children = imports.children[:] or [imports]
remove_comma = True
for child in children:
if remove_comma and getattr(child, 'value', None) == ',':
child.remove()
else:
remove_comma ^= True
if unicode(children[-1]) == ',':
children[-1].remove()
# If there are no imports left, just get rid of the entire statement
if not (imports.children or getattr(imports, 'value', None)):
p = node.get_prefix()
node = BlankLine()
node.prefix = p
return node