Changeset 391 for python/trunk/Lib/lib2to3/fixes
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 47 edited
- 1 copied
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Lib/lib2to3/fixes/fix_apply.py
r2 r391 13 13 14 14 class FixApply(fixer_base.BaseFix): 15 BM_compatible = True 15 16 16 17 PATTERN = """ -
python/trunk/Lib/lib2to3/fixes/fix_basestring.py
r2 r391 7 7 8 8 class FixBasestring(fixer_base.BaseFix): 9 BM_compatible = True 9 10 10 11 PATTERN = "'basestring'" -
python/trunk/Lib/lib2to3/fixes/fix_buffer.py
r2 r391 10 10 11 11 class FixBuffer(fixer_base.BaseFix): 12 BM_compatible = True 12 13 13 14 explicit = True # The user must ask for this fixer -
python/trunk/Lib/lib2to3/fixes/fix_callable.py
r2 r391 12 12 13 13 class FixCallable(fixer_base.BaseFix): 14 BM_compatible = True 15 16 order = "pre" 14 17 15 18 # Ignore callable(*args) or use of keywords. -
python/trunk/Lib/lib2to3/fixes/fix_dict.py
r2 r391 41 41 42 42 class FixDict(fixer_base.BaseFix): 43 BM_compatible = True 44 43 45 PATTERN = """ 44 46 power< head=any+ -
python/trunk/Lib/lib2to3/fixes/fix_except.py
r2 r391 35 35 36 36 class FixExcept(fixer_base.BaseFix): 37 BM_compatible = True 37 38 38 39 PATTERN = """ -
python/trunk/Lib/lib2to3/fixes/fix_exec.py
r2 r391 17 17 18 18 class FixExec(fixer_base.BaseFix): 19 BM_compatible = True 19 20 20 21 PATTERN = """ -
python/trunk/Lib/lib2to3/fixes/fix_execfile.py
r2 r391 14 14 15 15 class FixExecfile(fixer_base.BaseFix): 16 BM_compatible = True 16 17 17 18 PATTERN = """ -
python/trunk/Lib/lib2to3/fixes/fix_filter.py
r2 r391 20 20 21 21 class FixFilter(fixer_base.ConditionalFix): 22 BM_compatible = True 22 23 23 24 PATTERN = """ -
python/trunk/Lib/lib2to3/fixes/fix_funcattrs.py
r2 r391 8 8 9 9 class FixFuncattrs(fixer_base.BaseFix): 10 BM_compatible = True 11 10 12 PATTERN = """ 11 13 power< any+ trailer< '.' attr=('func_closure' | 'func_doc' | 'func_globals' -
python/trunk/Lib/lib2to3/fixes/fix_future.py
r2 r391 10 10 11 11 class FixFuture(fixer_base.BaseFix): 12 BM_compatible = True 13 12 14 PATTERN = """import_from< 'from' module_name="__future__" 'import' any >""" 13 15 -
python/trunk/Lib/lib2to3/fixes/fix_getcwdu.py
r2 r391 9 9 10 10 class FixGetcwdu(fixer_base.BaseFix): 11 BM_compatible = True 11 12 12 13 PATTERN = """ -
python/trunk/Lib/lib2to3/fixes/fix_has_key.py
r2 r391 38 38 39 39 class FixHasKey(fixer_base.BaseFix): 40 BM_compatible = True 40 41 41 42 PATTERN = """ -
python/trunk/Lib/lib2to3/fixes/fix_idioms.py
r2 r391 36 36 37 37 class FixIdioms(fixer_base.BaseFix): 38 39 38 explicit = True # The user must ask for this fixer 40 39 -
python/trunk/Lib/lib2to3/fixes/fix_import.py
r2 r391 37 37 38 38 class FixImport(fixer_base.BaseFix): 39 BM_compatible = True 39 40 40 41 PATTERN = """ … … 44 45 """ 45 46 47 def start_tree(self, tree, name): 48 super(FixImport, self).start_tree(tree, name) 49 self.skip = "absolute_import" in tree.future_features 50 46 51 def transform(self, node, results): 52 if self.skip: 53 return 47 54 imp = results['imp'] 48 55 … … 72 79 return 73 80 74 new = FromImport( '.', [imp])81 new = FromImport(u".", [imp]) 75 82 new.prefix = node.prefix 76 83 return new 77 84 78 85 def probably_a_local_import(self, imp_name): 79 imp_name = imp_name.split('.', 1)[0] 86 if imp_name.startswith(u"."): 87 # Relative imports are certainly not local imports. 88 return False 89 imp_name = imp_name.split(u".", 1)[0] 80 90 base_path = dirname(self.filename) 81 91 base_path = join(base_path, imp_name) 82 92 # If there is no __init__.py next to the file its not in a package 83 93 # so can't be a relative import. 84 if not exists(join(dirname(base_path), '__init__.py')):94 if not exists(join(dirname(base_path), "__init__.py")): 85 95 return False 86 for ext in [ '.py', sep, '.pyc', '.so', '.sl', '.pyd']:96 for ext in [".py", sep, ".pyc", ".so", ".sl", ".pyd"]: 87 97 if exists(base_path + ext): 88 98 return True -
python/trunk/Lib/lib2to3/fixes/fix_imports.py
r2 r391 85 85 class FixImports(fixer_base.BaseFix): 86 86 87 BM_compatible = True 88 keep_line_order = True 87 89 # This is overridden in fix_imports2. 88 90 mapping = MAPPING -
python/trunk/Lib/lib2to3/fixes/fix_input.py
r2 r391 12 12 13 13 class FixInput(fixer_base.BaseFix): 14 14 BM_compatible = True 15 15 PATTERN = """ 16 16 power< 'input' args=trailer< '(' [any] ')' > > -
python/trunk/Lib/lib2to3/fixes/fix_intern.py
r2 r391 13 13 14 14 class FixIntern(fixer_base.BaseFix): 15 BM_compatible = True 16 order = "pre" 15 17 16 18 PATTERN = """ -
python/trunk/Lib/lib2to3/fixes/fix_isinstance.py
r2 r391 15 15 16 16 class FixIsinstance(fixer_base.BaseFix): 17 17 BM_compatible = True 18 18 PATTERN = """ 19 19 power< -
python/trunk/Lib/lib2to3/fixes/fix_itertools.py
r2 r391 13 13 14 14 class FixItertools(fixer_base.BaseFix): 15 it_funcs = "('imap'|'ifilter'|'izip'|'ifilterfalse')" 15 BM_compatible = True 16 it_funcs = "('imap'|'ifilter'|'izip'|'izip_longest'|'ifilterfalse')" 16 17 PATTERN = """ 17 18 power< it='itertools' … … 28 29 prefix = None 29 30 func = results['func'][0] 30 if 'it' in results and func.value != u'ifilterfalse': 31 if ('it' in results and 32 func.value not in (u'ifilterfalse', u'izip_longest')): 31 33 dot, it = (results['dot'], results['it']) 32 34 # Remove the 'itertools' 33 35 prefix = it.prefix 34 36 it.remove() 35 # Replace the node w ich contains ('.', 'function') with the36 # function (to be consist ant with the second part of the pattern)37 # Replace the node which contains ('.', 'function') with the 38 # function (to be consistent with the second part of the pattern) 37 39 dot.remove() 38 40 func.parent.replace(func) -
python/trunk/Lib/lib2to3/fixes/fix_itertools_imports.py
r2 r391 7 7 8 8 class FixItertoolsImports(fixer_base.BaseFix): 9 BM_compatible = True 9 10 PATTERN = """ 10 11 import_from< 'from' 'itertools' 'import' imports=any > … … 21 22 member = child.value 22 23 name_node = child 24 elif child.type == token.STAR: 25 # Just leave the import as is. 26 return 23 27 else: 24 28 assert child.type == syms.import_as_name … … 28 32 child.value = None 29 33 child.remove() 30 elif member_name == u'ifilterfalse':34 elif member_name in (u'ifilterfalse', u'izip_longest'): 31 35 node.changed() 32 name_node.value = u'filterfalse' 36 name_node.value = (u'filterfalse' if member_name[1] == u'f' 37 else u'zip_longest') 33 38 34 39 # Make sure the import statement is still sane … … 41 46 remove_comma ^= True 42 47 43 ifchildren[-1].type == token.COMMA:44 children [-1].remove()48 while children and children[-1].type == token.COMMA: 49 children.pop().remove() 45 50 46 51 # If there are no imports left, just get rid of the entire statement 47 if not (imports.children or getattr(imports, 'value', None)) or \48 imports.parent is None:52 if (not (imports.children or getattr(imports, 'value', None)) or 53 imports.parent is None): 49 54 p = node.prefix 50 55 node = BlankLine() -
python/trunk/Lib/lib2to3/fixes/fix_long.py
r2 r391 11 11 12 12 class FixLong(fixer_base.BaseFix): 13 13 BM_compatible = True 14 14 PATTERN = "'long'" 15 15 -
python/trunk/Lib/lib2to3/fixes/fix_map.py
r2 r391 27 27 28 28 class FixMap(fixer_base.ConditionalFix): 29 BM_compatible = True 29 30 30 31 PATTERN = """ -
python/trunk/Lib/lib2to3/fixes/fix_metaclass.py
r2 r391 49 49 for node in cls_node.children: 50 50 if node.type == syms.suite: 51 # already in the prefer ed format, do nothing51 # already in the preferred format, do nothing 52 52 return 53 53 … … 72 72 """ if there is a semi-colon all the parts count as part of the same 73 73 simple_stmt. We just want the __metaclass__ part so we move 74 everything efter the semi-colon into its own simple_stmt node74 everything after the semi-colon into its own simple_stmt node 75 75 """ 76 76 for semi_ind, node in enumerate(stmt_node.children): … … 144 144 145 145 class FixMetaclass(fixer_base.BaseFix): 146 BM_compatible = True 146 147 147 148 PATTERN = """ -
python/trunk/Lib/lib2to3/fixes/fix_methodattrs.py
r2 r391 14 14 15 15 class FixMethodattrs(fixer_base.BaseFix): 16 BM_compatible = True 16 17 PATTERN = """ 17 18 power< any+ trailer< '.' attr=('im_func' | 'im_self' | 'im_class') > any* > -
python/trunk/Lib/lib2to3/fixes/fix_next.py
r2 r391 16 16 17 17 class FixNext(fixer_base.BaseFix): 18 BM_compatible = True 18 19 PATTERN = """ 19 20 power< base=any+ trailer< '.' attr='next' > trailer< '(' ')' > > -
python/trunk/Lib/lib2to3/fixes/fix_nonzero.py
r2 r391 7 7 8 8 class FixNonzero(fixer_base.BaseFix): 9 BM_compatible = True 9 10 PATTERN = """ 10 11 classdef< 'class' any+ ':' -
python/trunk/Lib/lib2to3/fixes/fix_operator.py
r2 r391 1 """Fixer for operator .{isCallable,sequenceIncludes}1 """Fixer for operator functions. 2 2 3 operator.isCallable(obj) -> hasattr(obj, '__call__')3 operator.isCallable(obj) -> hasattr(obj, '__call__') 4 4 operator.sequenceIncludes(obj) -> operator.contains(obj) 5 operator.isSequenceType(obj) -> isinstance(obj, collections.Sequence) 6 operator.isMappingType(obj) -> isinstance(obj, collections.Mapping) 7 operator.isNumberType(obj) -> isinstance(obj, numbers.Number) 8 operator.repeat(obj, n) -> operator.mul(obj, n) 9 operator.irepeat(obj, n) -> operator.imul(obj, n) 5 10 """ 6 11 7 12 # Local imports 8 from .. import fixer_base 9 from ..fixer_util import Call, Name, String 13 from lib2to3 import fixer_base 14 from lib2to3.fixer_util import Call, Name, String, touch_import 15 16 17 def invocation(s): 18 def dec(f): 19 f.invocation = s 20 return f 21 return dec 22 10 23 11 24 class FixOperator(fixer_base.BaseFix): 25 BM_compatible = True 26 order = "pre" 12 27 13 methods = "method=('isCallable'|'sequenceIncludes')" 14 func = "'(' func=any ')'" 28 methods = """ 29 method=('isCallable'|'sequenceIncludes' 30 |'isSequenceType'|'isMappingType'|'isNumberType' 31 |'repeat'|'irepeat') 32 """ 33 obj = "'(' obj=any ')'" 15 34 PATTERN = """ 16 35 power< module='operator' 17 trailer< '.' {methods} > trailer< {func}> >36 trailer< '.' %(methods)s > trailer< %(obj)s > > 18 37 | 19 power< {methods} trailer< {func}> >20 """ .format(methods=methods, func=func)38 power< %(methods)s trailer< %(obj)s > > 39 """ % dict(methods=methods, obj=obj) 21 40 22 41 def transform(self, node, results): 42 method = self._check_method(node, results) 43 if method is not None: 44 return method(node, results) 45 46 @invocation("operator.contains(%s)") 47 def _sequenceIncludes(self, node, results): 48 return self._handle_rename(node, results, u"contains") 49 50 @invocation("hasattr(%s, '__call__')") 51 def _isCallable(self, node, results): 52 obj = results["obj"] 53 args = [obj.clone(), String(u", "), String(u"'__call__'")] 54 return Call(Name(u"hasattr"), args, prefix=node.prefix) 55 56 @invocation("operator.mul(%s)") 57 def _repeat(self, node, results): 58 return self._handle_rename(node, results, u"mul") 59 60 @invocation("operator.imul(%s)") 61 def _irepeat(self, node, results): 62 return self._handle_rename(node, results, u"imul") 63 64 @invocation("isinstance(%s, collections.Sequence)") 65 def _isSequenceType(self, node, results): 66 return self._handle_type2abc(node, results, u"collections", u"Sequence") 67 68 @invocation("isinstance(%s, collections.Mapping)") 69 def _isMappingType(self, node, results): 70 return self._handle_type2abc(node, results, u"collections", u"Mapping") 71 72 @invocation("isinstance(%s, numbers.Number)") 73 def _isNumberType(self, node, results): 74 return self._handle_type2abc(node, results, u"numbers", u"Number") 75 76 def _handle_rename(self, node, results, name): 23 77 method = results["method"][0] 78 method.value = name 79 method.changed() 24 80 25 if method.value == u"sequenceIncludes": 26 if "module" not in results: 27 # operator may not be in scope, so we can't make a change. 28 self.warning(node, "You should use operator.contains here.") 81 def _handle_type2abc(self, node, results, module, abc): 82 touch_import(None, module, node) 83 obj = results["obj"] 84 args = [obj.clone(), String(u", " + u".".join([module, abc]))] 85 return Call(Name(u"isinstance"), args, prefix=node.prefix) 86 87 def _check_method(self, node, results): 88 method = getattr(self, "_" + results["method"][0].value.encode("ascii")) 89 if callable(method): 90 if "module" in results: 91 return method 29 92 else: 30 method.value = u"contains" 31 method.changed() 32 elif method.value == u"isCallable": 33 if "module" not in results: 34 self.warning(node, 35 "You should use hasattr(%s, '__call__') here." % 36 results["func"].value) 37 else: 38 func = results["func"] 39 args = [func.clone(), String(u", "), String(u"'__call__'")] 40 return Call(Name(u"hasattr"), args, prefix=node.prefix) 93 sub = (unicode(results["obj"]),) 94 invocation_str = unicode(method.invocation) % sub 95 self.warning(node, u"You should use '%s' here." % invocation_str) 96 return None -
python/trunk/Lib/lib2to3/fixes/fix_paren.py
r2 r391 11 11 # XXX This doesn't support nested for loops like [x for x in 1, 2 for x in 1, 2] 12 12 class FixParen(fixer_base.BaseFix): 13 BM_compatible = True 14 13 15 PATTERN = """ 14 16 atom< ('[' | '(') -
python/trunk/Lib/lib2to3/fixes/fix_print.py
r2 r391 28 28 29 29 class FixPrint(fixer_base.BaseFix): 30 31 BM_compatible = True 30 32 31 33 PATTERN = """ -
python/trunk/Lib/lib2to3/fixes/fix_raise.py
r2 r391 5 5 raise E, V -> raise E(V) 6 6 raise E, V, T -> raise E(V).with_traceback(T) 7 raise E, None, T -> raise E.with_traceback(T) 7 8 8 9 raise (((E, E'), E''), E'''), V -> raise E(V) … … 30 31 class FixRaise(fixer_base.BaseFix): 31 32 33 BM_compatible = True 32 34 PATTERN = """ 33 35 raise_stmt< 'raise' exc=any [',' val=any [',' tb=any]] > … … 38 40 39 41 exc = results["exc"].clone() 40 if exc.type is token.STRING: 41 self.cannot_convert(node, "Python 3 does not support string exceptions") 42 if exc.type == token.STRING: 43 msg = "Python 3 does not support string exceptions" 44 self.cannot_convert(node, msg) 42 45 return 43 46 … … 53 56 # exc.children[1].children[0] is the first element of the tuple 54 57 exc = exc.children[1].children[0].clone() 55 exc.prefix = " "58 exc.prefix = u" " 56 59 57 60 if "val" not in results: … … 72 75 tb.prefix = u"" 73 76 74 e = Call(exc, args) 77 e = exc 78 # If there's a traceback and None is passed as the value, then don't 79 # add a call, since the user probably just wants to add a 80 # traceback. See issue #9661. 81 if val.type != token.NAME or val.value != u"None": 82 e = Call(exc, args) 75 83 with_tb = Attr(e, Name(u'with_traceback')) + [ArgList([tb])] 76 84 new = pytree.Node(syms.simple_stmt, [Name(u"raise")] + with_tb) -
python/trunk/Lib/lib2to3/fixes/fix_raw_input.py
r2 r391 8 8 class FixRawInput(fixer_base.BaseFix): 9 9 10 BM_compatible = True 10 11 PATTERN = """ 11 12 power< name='raw_input' trailer< '(' [any] ')' > any* > -
python/trunk/Lib/lib2to3/fixes/fix_reduce.py
r2 r391 8 8 """ 9 9 10 from .. import pytree 11 from .. import fixer_base 12 from ..fixer_util import Name, Attr, touch_import 10 from lib2to3 import fixer_base 11 from lib2to3.fixer_util import touch_import 13 12 14 13 15 14 16 15 class FixReduce(fixer_base.BaseFix): 16 17 BM_compatible = True 18 order = "pre" 17 19 18 20 PATTERN = """ -
python/trunk/Lib/lib2to3/fixes/fix_renames.py
r2 r391 41 41 42 42 class FixRenames(fixer_base.BaseFix): 43 BM_compatible = True 43 44 PATTERN = "|".join(build_pattern()) 44 45 -
python/trunk/Lib/lib2to3/fixes/fix_repr.py
r2 r391 11 11 class FixRepr(fixer_base.BaseFix): 12 12 13 BM_compatible = True 13 14 PATTERN = """ 14 15 atom < '`' expr=any '`' > -
python/trunk/Lib/lib2to3/fixes/fix_set_literal.py
r2 r391 12 12 class FixSetLiteral(fixer_base.BaseFix): 13 13 14 BM_compatible = True 14 15 explicit = True 15 16 -
python/trunk/Lib/lib2to3/fixes/fix_standarderror.py
r2 r391 10 10 11 11 class FixStandarderror(fixer_base.BaseFix): 12 12 BM_compatible = True 13 13 PATTERN = """ 14 14 'StandardError' -
python/trunk/Lib/lib2to3/fixes/fix_sys_exc.py
r2 r391 14 14 class FixSysExc(fixer_base.BaseFix): 15 15 # This order matches the ordering of sys.exc_info(). 16 exc_info = ["exc_type", "exc_value", "exc_traceback"] 16 exc_info = [u"exc_type", u"exc_value", u"exc_traceback"] 17 BM_compatible = True 17 18 PATTERN = """ 18 19 power< 'sys' trailer< dot='.' attribute=(%s) > > -
python/trunk/Lib/lib2to3/fixes/fix_throw.py
r2 r391 15 15 16 16 class FixThrow(fixer_base.BaseFix): 17 17 BM_compatible = True 18 18 PATTERN = """ 19 19 power< any trailer< '.' 'throw' > -
python/trunk/Lib/lib2to3/fixes/fix_tuple_params.py
r2 r391 30 30 31 31 class FixTupleParams(fixer_base.BaseFix): 32 run_order = 4 #use a lower order since lambda is part of other 33 #patterns 34 BM_compatible = True 35 32 36 PATTERN = """ 33 37 funcdef< 'def' any parameters< '(' args=any ')' > … … 55 59 else: 56 60 start = 0 57 indent = "; "61 indent = u"; " 58 62 end = pytree.Leaf(token.INDENT, u"") 59 63 … … 155 159 d = {} 156 160 for i, obj in enumerate(param_list): 157 trailer = [Subscript(Number( i))]161 trailer = [Subscript(Number(unicode(i)))] 158 162 if isinstance(obj, list): 159 163 map_to_index(obj, trailer, d=d) -
python/trunk/Lib/lib2to3/fixes/fix_types.py
r2 r391 53 53 54 54 class FixTypes(fixer_base.BaseFix): 55 55 BM_compatible = True 56 56 PATTERN = '|'.join(_pats) 57 57 -
python/trunk/Lib/lib2to3/fixes/fix_unicode.py
r2 r391 1 """Fixer that changes unicode to str, unichr to chr, and u"..." into "...". 1 r"""Fixer for unicode. 2 3 * Changes unicode to str and unichr to chr. 4 5 * If "...\u..." is not unicode literal change it into "...\\u...". 6 7 * Change u"..." into "...". 2 8 3 9 """ 4 10 5 import re6 11 from ..pgen2 import token 7 12 from .. import fixer_base 8 13 9 14 _mapping = {u"unichr" : u"chr", u"unicode" : u"str"} 10 _literal_re = re.compile(ur"[uU][rR]?[\'\"]")11 15 12 16 class FixUnicode(fixer_base.BaseFix): 17 BM_compatible = True 18 PATTERN = "STRING | 'unicode' | 'unichr'" 13 19 14 PATTERN = "STRING | 'unicode' | 'unichr'" 20 def start_tree(self, tree, filename): 21 super(FixUnicode, self).start_tree(tree, filename) 22 self.unicode_literals = 'unicode_literals' in tree.future_features 15 23 16 24 def transform(self, node, results): … … 20 28 return new 21 29 elif node.type == token.STRING: 22 if _literal_re.match(node.value): 23 new = node.clone() 24 new.value = new.value[1:] 25 return new 30 val = node.value 31 if not self.unicode_literals and val[0] in u'\'"' and u'\\' in val: 32 val = ur'\\'.join([ 33 v.replace(u'\\u', ur'\\u').replace(u'\\U', ur'\\U') 34 for v in val.split(ur'\\') 35 ]) 36 if val[0] in u'uU': 37 val = val[1:] 38 if val == node.value: 39 return node 40 new = node.clone() 41 new.value = val 42 return new -
python/trunk/Lib/lib2to3/fixes/fix_urllib.py
r2 r391 6 6 7 7 # Local imports 8 from .fix_imports import alternates, FixImports 9 from .. import fixer_base 10 from ..fixer_util import Name, Comma, FromImport, Newline, attr_chain 8 from lib2to3.fixes.fix_imports import alternates, FixImports 9 from lib2to3 import fixer_base 10 from lib2to3.fixer_util import (Name, Comma, FromImport, Newline, 11 find_indentation, Node, syms) 11 12 12 MAPPING = { 'urllib': [13 ( 'urllib.request',14 [ 'URLOpener', 'FancyURLOpener', 'urlretrieve',15 '_urlopener', 'urlopen', 'urlcleanup',16 'pathname2url', 'url2pathname']),17 ( 'urllib.parse',18 [ 'quote', 'quote_plus', 'unquote', 'unquote_plus',19 'urlencode', 'splitattr', 'splithost', 'splitnport',20 'splitpasswd', 'splitport', 'splitquery', 'splittag',21 'splittype', 'splituser', 'splitvalue', ]),22 ( 'urllib.error',23 [ 'ContentTooShortError'])],24 'urllib2': [25 ( 'urllib.request',26 [ 'urlopen', 'install_opener', 'build_opener',27 'Request', 'OpenerDirector', 'BaseHandler',28 'HTTPDefaultErrorHandler', 'HTTPRedirectHandler',29 'HTTPCookieProcessor', 'ProxyHandler',30 'HTTPPasswordMgr',31 'HTTPPasswordMgrWithDefaultRealm',32 'AbstractBasicAuthHandler',33 'HTTPBasicAuthHandler', 'ProxyBasicAuthHandler',34 'AbstractDigestAuthHandler',35 'HTTPDigestAuthHandler', 'ProxyDigestAuthHandler',36 'HTTPHandler', 'HTTPSHandler', 'FileHandler',37 'FTPHandler', 'CacheFTPHandler',38 'UnknownHandler']),39 ( 'urllib.error',40 [ 'URLError', 'HTTPError']),13 MAPPING = {"urllib": [ 14 ("urllib.request", 15 ["URLopener", "FancyURLopener", "urlretrieve", 16 "_urlopener", "urlopen", "urlcleanup", 17 "pathname2url", "url2pathname"]), 18 ("urllib.parse", 19 ["quote", "quote_plus", "unquote", "unquote_plus", 20 "urlencode", "splitattr", "splithost", "splitnport", 21 "splitpasswd", "splitport", "splitquery", "splittag", 22 "splittype", "splituser", "splitvalue", ]), 23 ("urllib.error", 24 ["ContentTooShortError"])], 25 "urllib2" : [ 26 ("urllib.request", 27 ["urlopen", "install_opener", "build_opener", 28 "Request", "OpenerDirector", "BaseHandler", 29 "HTTPDefaultErrorHandler", "HTTPRedirectHandler", 30 "HTTPCookieProcessor", "ProxyHandler", 31 "HTTPPasswordMgr", 32 "HTTPPasswordMgrWithDefaultRealm", 33 "AbstractBasicAuthHandler", 34 "HTTPBasicAuthHandler", "ProxyBasicAuthHandler", 35 "AbstractDigestAuthHandler", 36 "HTTPDigestAuthHandler", "ProxyDigestAuthHandler", 37 "HTTPHandler", "HTTPSHandler", "FileHandler", 38 "FTPHandler", "CacheFTPHandler", 39 "UnknownHandler"]), 40 ("urllib.error", 41 ["URLError", "HTTPError"]), 41 42 ] 42 43 } … … 79 80 replacements. 80 81 """ 81 import_mod = results.get( 'module')82 import_mod = results.get("module") 82 83 pref = import_mod.prefix 83 84 … … 95 96 module. 96 97 """ 97 mod_member = results.get( 'mod_member')98 mod_member = results.get("mod_member") 98 99 pref = mod_member.prefix 99 member = results.get( 'member')100 member = results.get("member") 100 101 101 102 # Simple case with only a single member being imported … … 112 113 mod_member.replace(Name(new_name, prefix=pref)) 113 114 else: 114 self.cannot_convert(node, 115 'This is an invalid module element') 115 self.cannot_convert(node, "This is an invalid module element") 116 116 117 117 # Multiple members being imported … … 120 120 modules = [] 121 121 mod_dict = {} 122 members = results .get('members')122 members = results["members"] 123 123 for member in members: 124 member = member.value125 124 # we only care about the actual members 126 if member != ',': 125 if member.type == syms.import_as_name: 126 as_name = member.children[2].value 127 member_name = member.children[0].value 128 else: 129 member_name = member.value 130 as_name = None 131 if member_name != u",": 127 132 for change in MAPPING[mod_member.value]: 128 if member in change[1]: 129 if change[0] in mod_dict: 130 mod_dict[change[0]].append(member) 131 else: 132 mod_dict[change[0]] = [member] 133 if member_name in change[1]: 134 if change[0] not in mod_dict: 133 135 modules.append(change[0]) 136 mod_dict.setdefault(change[0], []).append(member) 134 137 135 138 new_nodes = [] 139 indentation = find_indentation(node) 140 first = True 141 def handle_name(name, prefix): 142 if name.type == syms.import_as_name: 143 kids = [Name(name.children[0].value, prefix=prefix), 144 name.children[1].clone(), 145 name.children[2].clone()] 146 return [Node(syms.import_as_name, kids)] 147 return [Name(name.value, prefix=prefix)] 136 148 for module in modules: 137 149 elts = mod_dict[module] 138 150 names = [] 139 151 for elt in elts[:-1]: 140 names.extend([Name(elt, prefix=pref), Comma()]) 141 names.append(Name(elts[-1], prefix=pref)) 142 new_nodes.append(FromImport(module, names)) 152 names.extend(handle_name(elt, pref)) 153 names.append(Comma()) 154 names.extend(handle_name(elts[-1], pref)) 155 new = FromImport(module, names) 156 if not first or node.parent.prefix.endswith(indentation): 157 new.prefix = indentation 158 new_nodes.append(new) 159 first = False 143 160 if new_nodes: 144 161 nodes = [] … … 148 165 node.replace(nodes) 149 166 else: 150 self.cannot_convert(node, 'All module elements are invalid')167 self.cannot_convert(node, "All module elements are invalid") 151 168 152 169 def transform_dot(self, node, results): 153 170 """Transform for calls to module members in code.""" 154 module_dot = results.get( 'bare_with_attr')155 member = results.get( 'member')171 module_dot = results.get("bare_with_attr") 172 member = results.get("member") 156 173 new_name = None 157 174 if isinstance(member, list): … … 165 182 prefix=module_dot.prefix)) 166 183 else: 167 self.cannot_convert(node, 'This is an invalid module element')184 self.cannot_convert(node, "This is an invalid module element") 168 185 169 186 def transform(self, node, results): 170 if results.get( 'module'):187 if results.get("module"): 171 188 self.transform_import(node, results) 172 elif results.get( 'mod_member'):189 elif results.get("mod_member"): 173 190 self.transform_member(node, results) 174 elif results.get( 'bare_with_attr'):191 elif results.get("bare_with_attr"): 175 192 self.transform_dot(node, results) 176 193 # Renaming and star imports are not supported for these modules. 177 elif results.get( 'module_star'):178 self.cannot_convert(node, 'Cannot handle star imports.')179 elif results.get( 'module_as'):180 self.cannot_convert(node, 'This module is now multiple modules')194 elif results.get("module_star"): 195 self.cannot_convert(node, "Cannot handle star imports.") 196 elif results.get("module_as"): 197 self.cannot_convert(node, "This module is now multiple modules") -
python/trunk/Lib/lib2to3/fixes/fix_xrange.py
r2 r391 11 11 12 12 class FixXrange(fixer_base.BaseFix): 13 13 BM_compatible = True 14 14 PATTERN = """ 15 15 power< … … 17 17 rest=any* > 18 18 """ 19 20 def start_tree(self, tree, filename): 21 super(FixXrange, self).start_tree(tree, filename) 22 self.transformed_xranges = set() 23 24 def finish_tree(self, tree, filename): 25 self.transformed_xranges = None 19 26 20 27 def transform(self, node, results): … … 30 37 name = results["name"] 31 38 name.replace(Name(u"range", prefix=name.prefix)) 39 # This prevents the new range call from being wrapped in a list later. 40 self.transformed_xranges.add(id(node)) 32 41 33 42 def transform_range(self, node, results): 34 if not self.in_special_context(node): 43 if (id(node) not in self.transformed_xranges and 44 not self.in_special_context(node)): 35 45 range_call = Call(Name(u"range"), [results["args"].clone()]) 36 46 # Encase the range call in list(). -
python/trunk/Lib/lib2to3/fixes/fix_xreadlines.py
r2 r391 10 10 11 11 class FixXreadlines(fixer_base.BaseFix): 12 BM_compatible = True 12 13 PATTERN = """ 13 14 power< call=any+ trailer< '.' 'xreadlines' > trailer< '(' ')' > > -
python/trunk/Lib/lib2to3/fixes/fix_zip.py
r2 r391 14 14 class FixZip(fixer_base.ConditionalFix): 15 15 16 BM_compatible = True 16 17 PATTERN = """ 17 18 power< 'zip' args=trailer< '(' [any] ')' >
Note:
See TracChangeset
for help on using the changeset viewer.