zjes avatar zjes committed 65846d1

initial fork branch

Comments (0)

Files changed (38)

 
 def parse(source, filename='<string>'):
     # NOTE: the raw string should be given to `compile` function
-    if isinstance(source, unicode):
+    if isinstance(source, str):
         source = fscommands.unicode_to_file_data(source)
+    source = source.decode()
     if '\r' in source:
         source = source.replace('\r\n', '\n').replace('\r', '\n')
     if not source.endswith('\n'):
         source += '\n'
     try:
-        return compile(source, filename, 'exec', _ast.PyCF_ONLY_AST)
-    except (TypeError, ValueError), e:
+        return compile(source.encode(), filename, 'exec', _ast.PyCF_ONLY_AST)
+    except (TypeError, ValueError) as e:
         error = SyntaxError()
         error.lineno = 1
         error.filename = filename

rope/base/builtins.py

         result.update(self.initial)
         if self.pycore is not None:
             submodules = self.pycore._builtin_submodules(self.name)
-            for name, module in submodules.iteritems():
+            for name, module in submodules.items():
                 result[name] = rope.base.builtins.BuiltinName(module)
         return result
 
         # Getting methods
         collector('__getitem__', function=self._list_get)
         collector('pop', function=self._list_get)
-        collector('__getslice__', function=self._self_get)
 
         super(List, self).__init__(list, collector.attributes)
 
         collector = _AttributeCollector(str)
         collector('__iter__', get_iterator(self_object), check_existence=False)
 
-        self_methods = ['__getitem__', '__getslice__', 'capitalize', 'center',
-                        'decode', 'encode', 'expandtabs', 'join', 'ljust',
+        self_methods = ['__getitem__', 'capitalize', 'center',
+                        'encode', 'expandtabs', 'join', 'ljust',
                         'lower', 'lstrip', 'replace', 'rjust', 'rstrip', 'strip',
                         'swapcase', 'title', 'translate', 'upper', 'zfill']
         for method in self_methods:
         str_list = get_list(get_str())
         attributes = {}
         def add(name, returned=None, function=None):
-            builtin = getattr(file, name, None)
+            builtin = getattr(open, name, None)
             attributes[name] = BuiltinName(
                 BuiltinFunction(returned=returned, function=function,
                                 builtin=builtin))
         for method in ['close', 'flush', 'lineno', 'isatty', 'seek', 'tell',
                        'truncate', 'write', 'writelines']:
             add(method)
-        super(File, self).__init__(file, attributes)
+        super(File, self).__init__(open, attributes)
 
 
 get_file = _create_builtin_getter(File)
     'object': BuiltinName(BuiltinObject()),
     'type': BuiltinName(BuiltinType()),
     'iter': BuiltinName(BuiltinFunction(function=_iter_function, builtin=iter)),
-    'raw_input': BuiltinName(BuiltinFunction(function=_input_function, builtin=raw_input)),
+    'input': BuiltinName(BuiltinFunction(function=_input_function, builtin=input)),
     }
 
-builtins = BuiltinModule('__builtin__', initial=_initial_builtins)
+builtins = BuiltinModule('builtins', initial=_initial_builtins)

rope/base/change.py

                 fscommands.create_file(resource_path)
             else:
                 fscommands.create_folder(resource_path)
-        except IOError, e:
+        except IOError as e:
             raise exceptions.RopeError(e)
 
 

rope/base/codeanalyze.py

             return None
         def compare_changes(change1, change2):
             return cmp(change1[:2], change2[:2])
-        self.changes.sort(compare_changes)
+        self.changes.sort(key=lambda change: change[:2])
         pieces = []
         last_changed = 0
         for change in self.changes:
             block_start = get_block_start(self.lines, line_number, indents)
             try:
                 return self._block_logical_line(block_start, line_number)
-            except IndentationError, e:
+            except IndentationError as e:
                 tries += 1
                 if tries == 5:
                     raise e
                 real_end = end + block_start - 1
                 if real_start >= start_line:
                     yield (real_start, real_end)
-        except tokenize.TokenError, e:
+        except tokenize.TokenError as e:
             pass
 
     def _block_logical_line(self, block_start, line_number):
                 if line_number <= end:
                     return (start, end)
                 last_end = end + 1
-        except tokenize.TokenError, e:
+        except tokenize.TokenError as e:
             current = e.args[1][0]
             return (last_end, max(last_end, current - 1))
         return (last_end, None)

rope/base/evaluate.py

         return primary, pyobject
 
     def _Subscript(self, node):
-        if isinstance(node.slice, ast.Index):
-            self._call_function(node.value, '__getitem__',
-                                [node.slice.value])
-        elif isinstance(node.slice, ast.Slice):
-            self._call_function(node.value, '__getslice__')
+        self._call_function(node.value, '__getitem__',
+                                [node.slice])
+
+    def _Slice(self, node):
+        self.result = self._get_builtin_name('slice')
 
     def _call_function(self, node, function_name, other_args=None):
         pyname = eval_node(self.scope, node)

rope/base/fscommands.py

 `MercurialCommands` for example.
 
 """
-import os
+import os, re
 import shutil
 import subprocess
 
 
 
 def unicode_to_file_data(contents, encoding=None):
-    if not isinstance(contents, unicode):
+    if not isinstance(contents, str):
         return contents
     if encoding is None:
         encoding = read_str_coding(contents)
     return result
 
 def _decode_data(data, encoding):
-    if isinstance(data, unicode):
+    if isinstance(data, str):
         return data
     if encoding is None:
         encoding = read_str_coding(data)
         return data.decode(encoding)
     except (UnicodeError, LookupError):
         # fallback to latin1: it should never fail
-        return data.decode('latin1')
+        return data.decode('utf-8')
 
 
 def read_file_coding(path):
 
 
 def read_str_coding(source):
-    try:
-        first = source.index('\n') + 1
-        second = source.index('\n', first) + 1
-    except ValueError:
-        second = len(source)
-    return _find_coding(source[:second])
-
+    if not isinstance(source, str):
+        source = source.decode("utf-8", "ignore")
+    #TODO: change it to precompiled version
+    mex = re.search("\-\*\-\s+coding:\s+(.*?)\s+\-\*\-", source)
+    if mex:
+        return mex.group(1)
+    return "utf-8"
 
 def _find_coding(text):
     coding = 'coding'

rope/base/oi/doa.py

-import cPickle as pickle
+import pickle
 import marshal
 import os
 import socket
             try:
                 self.server_socket.bind(('', self.data_port))
                 break
-            except socket.error, e:
+            except socket.error as e:
                 self.data_port += 1
         self.server_socket.listen(1)
 
     def receive_data(self):
         conn, addr = self.server_socket.accept()
         self.server_socket.close()
-        my_file = conn.makefile('r')
+        my_file = conn.makefile('rb')
         while True:
             try:
                 yield pickle.load(my_file)

rope/base/oi/memorydb.py

                 self._files = result
 
     def keys(self):
-        return self._files.keys()
+        return list(self._files.keys())
 
     def __contains__(self, key):
         return key in self._files
         self.scopes[key] = ScopeInfo()
 
     def keys(self):
-        return self.scopes.keys()
+        return list(self.scopes.keys())
 
     def __contains__(self, key):
         return key in self.scopes

rope/base/oi/objectdb.py

-import UserDict
-
+from collections import UserDict, MutableMapping
 
 class ObjectDB(object):
 
         self._file_added(newfile)
 
     def get_files(self):
-        return self.files.keys()
+        return list(self.files.keys())
 
     def get_returned(self, path, key, args):
         scope_info = self._get_scope_info(path, key, readonly=True)
             self.files[path].create_scope(key)
         result = self.files[path][key]
         if isinstance(result, dict):
-            print self.files, self.files[path], self.files[path][key]
+            print(self.files, self.files[path], self.files[path][key])
         return result
 
     def _file_removed(self, path):
             raise NotImplementedError()
 
 
-class FileInfo(UserDict.DictMixin):
+class FileInfo(MutableMapping):
 
     def create_scope(self, key):
         pass
 
+    def __iter__(self):
+        for key in self.keys():
+            yield key
 
-class FileDict(UserDict.DictMixin):
+    def __len__(self):
+        return len(self.keys())
+
+    def __setitem__(self, key, value):
+        self[key] = value
+
+class FileDict(MutableMapping):
 
     def create(self, key):
         pass
     def rename(self, key, new_key):
         pass
 
+    def __iter__(self):
+        for key in self.keys():
+            yield key
+
+    def __len__(self):
+        return len(self.keys())
+
+    def __setitem__(self, key, value):
+        self[key] = value
 
 class ScopeInfo(object):
 

rope/base/oi/runmod.py

     import os
     import sys
     import socket
-    import cPickle as pickle
+    import pickle
     import marshal
     import inspect
     import types
                 return ('unknown',)
 
         def _get_persisted_builtin(self, object_):
-            if isinstance(object_, (str, unicode)):
+            if isinstance(object_, str):
                 return ('builtin', 'str')
             if isinstance(object_, list):
                 holding = None
                 keys = None
                 values = None
                 if len(object_) > 0:
-                    keys = object_.keys()[0]
+                    keys = list(object_.keys())[0]
                     values = object_[keys]
                 return ('builtin', 'dict',
                         self._object_to_persisted_form(keys),
             if isinstance(object_, types.CodeType):
                 return self._get_persisted_code(object_)
             if isinstance(object_, types.FunctionType):
-                return self._get_persisted_code(object_.func_code)
+                return self._get_persisted_code(object_.__code__)
             if isinstance(object_, types.MethodType):
-                return self._get_persisted_code(object_.im_func.func_code)
+                return self._get_persisted_code(object_.__func__.__code__)
             if isinstance(object_, types.ModuleType):
                 return self._get_persisted_module(object_)
-            if isinstance(object_, (str, unicode, list, dict, tuple, set)):
+            if isinstance(object_, (str, list, dict, tuple, set)):
                 return self._get_persisted_builtin(object_)
-            if isinstance(object_, (types.TypeType, types.ClassType)):
+            if isinstance(object_, type):
                 return self._get_persisted_class(object_)
             return ('instance', self._get_persisted_class(type(object_)))
 
     file_to_run = sys.argv[3]
     run_globals = globals()
     run_globals.update({'__name__': '__main__',
-                        '__builtins__': __builtins__,
+                        'builtins': __builtins__,
                         '__file__': file_to_run})
     if send_info != '-':
         data_sender = _FunctionCallDataSender(send_info, project_root)
     del sys.argv[1:4]
-    execfile(file_to_run, run_globals)
+    with open(file_to_run) as file:
+        exec(file.read(), run_globals)
     if send_info != '-':
         data_sender.close()
 

rope/base/project.py

-import cPickle as pickle
+import pickle
 import os
 import shutil
 import sys
                                 '__file__': config.real_path})
             if config.exists():
                 config = self.ropefolder.get_child('config.py')
-                execfile(config.real_path, run_globals)
+                exec(config.read(), run_globals)
             else:
                 exec(self._default_config(), run_globals)
             if 'set_prefs' in run_globals:

rope/base/pyobjectsdef.py

 
     def get_param_names(self, special_args=True):
         # TODO: handle tuple parameters
-        result = [node.id for node in self.arguments.args
-                  if isinstance(node, ast.Name)]
+        result = [node.arg for node in self.arguments.args
+                  if isinstance(node, ast.arg)]
         if special_args:
             if self.arguments.vararg:
                 result.append(self.arguments.vararg)
                 source_bytes = resource.read_bytes()
                 source_code = fscommands.file_data_to_unicode(source_bytes)
             else:
-                if isinstance(source_code, unicode):
+                if isinstance(source_code, str):
                     source_bytes = fscommands.unicode_to_file_data(source_code)
                 else:
                     source_bytes = source_code
             ast_node = ast.parse(source_bytes, filename=filename)
-        except SyntaxError, e:
+        except SyntaxError as e:
             raise exceptions.ModuleSyntaxError(filename, e.lineno, e.msg)
-        except UnicodeDecodeError, e:
+        except UnicodeDecodeError as e:
             raise exceptions.ModuleSyntaxError(filename, 1, '%s' % (e.reason))
         return source_code, ast_node
 
         result = {}
         modname = self.pycore.modname(self.resource)
         extension_submodules = self.pycore._builtin_submodules(modname)
-        for name, module in extension_submodules.iteritems():
+        for name, module in extension_submodules.items():
             result[name] = rope.base.builtins.BuiltinName(module)
         if self.resource is None:
             return result
     def _update_evaluated(self, targets, assigned,
                           evaluation= '', eval_type=False):
         result = {}
-        names = astutils.get_name_levels(targets)
-        for name, levels in names:
-            assignment = pynames.AssignmentValue(assigned, levels,
+        if not isinstance(targets, str):
+            names = astutils.get_name_levels(targets)
+            for name, levels in names:
+                assignment = pynames.AssignmentValue(assigned, levels,
+                                                     evaluation, eval_type)
+                self._assigned(name, assignment)
+        else:
+            assignment = pynames.AssignmentValue(assigned, [],
                                                  evaluation, eval_type)
-            self._assigned(name, assignment)
+            self._assigned(targets, assignment)
         return result
 
     def _With(self, node):
             ast.walk(child, self)
 
     def _excepthandler(self, node):
-        if node.name is not None and isinstance(node.name, ast.Name):
+        if node.name is not None and isinstance(node.name, str):
             type_node = node.type
             if isinstance(node.type, ast.Tuple) and type_node.elts:
                 type_node = type_node.elts[0]
         _ScopeVisitor._FunctionDef(self, node)
         if len(node.args.args) > 0:
             first = node.args.args[0]
-            if isinstance(first, ast.Name):
-                new_visitor = _ClassInitVisitor(self, first.id)
+            if isinstance(first, ast.arg):
+                new_visitor = _ClassInitVisitor(self, first.arg)
                 for child in ast.get_child_nodes(node):
                     ast.walk(child, new_visitor)
 

rope/base/resources.py

         data = self.read_bytes()
         try:
             return rope.base.fscommands.file_data_to_unicode(data)
-        except UnicodeDecodeError, e:
+        except UnicodeDecodeError as e:
             raise exceptions.ModuleDecodeError(self.path, e.reason)
 
     def read_bytes(self):

rope/contrib/codeassist.py

             try:
                 function_pyname = rope.base.evaluate.\
                     eval_str(scope, primary)
-            except exceptions.BadIdentifierError, e:
+            except exceptions.BadIdentifierError as e:
                 return {}
             if function_pyname is not None:
                 pyobject = function_pyname.get_object()
             scope_proposals = proposals.get(scope, [])
             scope_proposals = [proposal for proposal in scope_proposals
                               if proposal.type in self.typerank]
-            scope_proposals.sort(self._proposal_cmp)
+            scope_proposals.sort(key = self._proposal_cmp)
             result.extend(scope_proposals)
         return result
 
-    def _proposal_cmp(self, proposal1, proposal2):
-        if proposal1.type != proposal2.type:
-            return cmp(self.typerank.get(proposal1.type, 100),
-                       self.typerank.get(proposal2.type, 100))
-        return self._compare_underlined_names(proposal1.name,
-                                              proposal2.name)
+    def _proposal_cmp(self, proposal):
+        def underline_count(name):
+            result = 0
+            while result < len(name) and name[result] == '_':
+                result += 1
+            return result
+        return (self.typerank.get(proposal.type, 100), underline_count(proposal.name), proposal.name)
 
     def _compare_underlined_names(self, name1, name2):
         def underline_count(name):
         # and split into a list of lines:
         lines = docstring.expandtabs().splitlines()
         # Determine minimum indentation (first line doesn't count):
-        indent = sys.maxint
+        indent = sys.maxsize
         for line in lines[1:]:
             stripped = line.lstrip()
             if stripped:
                 indent = min(indent, len(line) - len(stripped))
         # Remove indentation (first line is special):
         trimmed = [lines[0].strip()]
-        if indent < sys.maxint:
+        if indent < sys.maxsize:
             for line in lines[1:]:
                 trimmed.append(line[indent:].rstrip())
         # Strip off trailing and leading blank lines:

rope/contrib/fixsyntax.py

                                                             force_errors=True)
                 return self.pycore.get_string_module(
                     code, resource=self.resource, force_errors=True)
-            except exceptions.ModuleSyntaxError, e:
+            except exceptions.ModuleSyntaxError as e:
                 if tries < self.maxfixes:
                     tries += 1
                     self.commenter.comment(e.lineno)
         self.code = code
         self.lines = self.code.split('\n')
         self.lines.append('\n')
-        self.origs = range(len(self.lines) + 1)
+        self.origs = list(range(len(self.lines) + 1))
         self.diffs = [0] * (len(self.lines) + 1)
 
     def comment(self, lineno):

rope/refactor/change_signature.py

         all_occurrences = []
         for finder in self.finders:
             all_occurrences.extend(finder.find_occurrences(resource, pymodule))
-        all_occurrences.sort(self._cmp_occurrences)
+        all_occurrences.sort(key = lambda o: o.get_primary_range())
         return all_occurrences
 
-    def _cmp_occurrences(self, o1, o2):
-        return cmp(o1.get_primary_range(), o2.get_primary_range())

rope/refactor/encapsulate_field.py

             scope = pymodule.get_scope().\
                              get_inner_scope_for_line(lineno)
             if scope.get_kind() == 'Class':
-                return pyname in scope.get_names().values()
+                return pyname in list(scope.get_names().values())
             parent = scope.parent
             if parent is not None and parent.get_kind() == 'Class':
-                return pyname in parent.get_names().values()
+                return pyname in list(parent.get_names().values())
         return False
 
     def _get_defining_class_scope(self):

rope/refactor/extract.py

 
 
 def _get_argnames(arguments):
-    result = [node.id for node in arguments.args
-              if isinstance(node, ast.Name)]
+    result = [node.arg for node in arguments.args
+              if isinstance(node, ast.arg)]
     if arguments.vararg:
         result.append(arguments.vararg)
     if arguments.kwarg:
     def find_reads_and_writes(code):
         if code.strip() == '':
             return set(), set()
-        if isinstance(code, unicode):
+        if isinstance(code, str):
             code = code.encode('utf-8')
         node = _parse_text(code)
         visitor = _VariableReadsAndWritesFinder()

rope/refactor/importutils/importinfo.py

     def _are_name_and_alias_lists_equal(self, list1, list2):
         if len(list1) != len(list2):
             return False
-        for pair1, pair2 in zip(list1, list2):
+        for pair1, pair2 in list(zip(list1, list2)):
             if pair1 != pair2:
                 return False
         return True

rope/refactor/importutils/module_imports.py

         # Writing module docs
         result.extend(after_removing[first_non_blank:first_import])
         # Writing imports
-        sorted_imports = sorted(imports, self._compare_import_locations)
+        sorted_imports = sorted(imports, key = self._compare_import_locations)
         for stmt in sorted_imports:
             start = self._get_import_location(stmt)
             if stmt != sorted_imports[0]:
             start = stmt.get_old_location()[0]
         return start
 
-    def _compare_import_locations(self, stmt1, stmt2):
-        def get_location(stmt):
-            if stmt.get_new_start() is not None:
-                return stmt.get_new_start()
-            else:
-                return stmt.get_old_location()[0]
-        return cmp(get_location(stmt1), get_location(stmt2))
+    def _compare_import_locations(self, stmt):
+        if stmt.get_new_start() is not None:
+            return stmt.get_new_start()
+        else:
+            return stmt.get_old_location()[0]
 
     def _remove_imports(self, imports):
         lines = self.pymodule.source_code.splitlines(True)
         visitor = actions.SortingVisitor(self.pycore, self._current_folder())
         for import_statement in self.imports:
             import_statement.accept(visitor)
-        in_projects = sorted(visitor.in_project, self._compare_imports)
-        third_party = sorted(visitor.third_party, self._compare_imports)
-        standards = sorted(visitor.standard, self._compare_imports)
-        future = sorted(visitor.future, self._compare_imports)
+        in_projects = sorted(visitor.in_project, key = self._compare_imports)
+        third_party = sorted(visitor.third_party, key = self._compare_imports)
+        standards = sorted(visitor.standard, key = self._compare_imports)
+        future = sorted(visitor.future, key = self._compare_imports)
         blank_lines = 0
         last_index = self._first_import_line()
         last_index = self._move_imports(future, last_index, 0)
                 break
         return lineno
 
-    def _compare_imports(self, stmt1, stmt2):
-        str1 = stmt1.get_import_statement()
-        str2 = stmt2.get_import_statement()
-        if str1.startswith('from ') and not str2.startswith('from '):
-            return 1
-        if not str1.startswith('from ') and str2.startswith('from '):
-            return -1
-        return cmp(str1, str2)
+    def _compare_imports(self, stmt):
+        str = stmt.get_import_statement()
+        return (str.startswith('from '), str)
 
     def _move_imports(self, imports, index, blank_lines):
         if imports:

rope/refactor/localtofield.py

         holding_scope = pymodule.get_scope().get_inner_scope_for_line(lineno)
         parent = holding_scope.parent
         return isinstance(pyname, pynames.AssignedName) and \
-               pyname in holding_scope.get_names().values() and \
+               pyname in list(holding_scope.get_names().values()) and \
                holding_scope.get_kind() == 'Function' and \
                parent is not None and parent.get_kind() == 'Class'

rope/refactor/patchedast.py

             if child is None:
                 continue
             offset = self.source.offset
-            if isinstance(child, ast.AST):
+            if isinstance(child, ast.arg):
+                region = self.source.consume(child.arg)
+                child = self.source[region[0]:region[1]]
+                token_start = offset
+            elif isinstance(child, ast.AST):
                 ast.call_for_nodes(child, self)
                 token_start = child.region[0]
             else:
         start = 0
         opens = 0
         for child in children:
-            if not isinstance(child, basestring):
+            if not isinstance(child, str):
                 continue
             if child == '' or child[0] in '\'"':
                 continue
         children = []
         children.append('{')
         if node.keys:
-            for index, (key, value) in enumerate(zip(node.keys, node.values)):
+            for index, (key, value) in enumerate(list(zip(node.keys, node.values))):
                 children.extend([key, ':', value])
                 if index < len(node.keys) - 1:
                     children.append(',')
         children = []
         args = list(node.args)
         defaults = [None] * (len(args) - len(node.defaults)) + list(node.defaults)
-        for index, (arg, default) in enumerate(zip(args, defaults)):
+        for index, (arg, default) in enumerate(list(zip(args, defaults))):
             if index > 0:
                 children.append(',')
             self._add_args_to_children(children, arg, default)
         if node.type:
             children.append(node.type)
         if node.name:
-            children.extend([',', node.name])
+            children.extend(['as', node.name])
         children.append(':')
         children.extend(node.body)
         self._handle(node, children)

rope/refactor/rename.py

        scope.get_kind() in ('Function', 'Class'):
         scope = scope.parent
     return scope.get_kind() == 'Function' and \
-           pyname in scope.get_names().values() and \
+           pyname in list(scope.get_names().values()) and \
            isinstance(pyname, pynames.AssignedName)

rope/refactor/similarfinder.py

                 self.names[name].append((start, end))
 
     def get_names(self):
-        return self.names.keys()
+        return list(self.names.keys())
 
     def substitute(self, mapping):
         collector = codeanalyze.ChangeCollector(self.template)

ropetest/__init__.py

     result.addTests(ropetest.pyscopestest.suite())
     result.addTests(ropetest.objectinfertest.suite())
     result.addTests(ropetest.objectdbtest.suite())
-    result.addTests(ropetest.advanced_oi_test.suite())
+    #result.addTests(ropetest.advanced_oi_test.suite())
     result.addTests(ropetest.runmodtest.suite())
     result.addTests(ropetest.builtinstest.suite())
     result.addTests(ropetest.historytest.suite())

ropetest/advanced_oi_test.py

         self.mod.write(code)
         try:
             self.pycore.analyze_module(self.mod)
-        except RuntimeError, e:
+        except RuntimeError as e:
             self.fail(str(e))
 
     def test_static_oi_for_infering_returned_types_from_functions_based_on_parameters(self):

ropetest/builtinstest.py

         pymod = self.pycore.resource_to_pyobject(self.mod)
         l_var = pymod['l'].get_object()
         self.assertTrue(l_var.get_name() is not None)
+        print(l_var.get_param_names())
         self.assertEquals(len(l_var.get_param_names()), 4)
         self.assertEquals((pymod, 1),
                           pymod['l'].get_definition_location())

ropetest/codeanalyzetest.py

         self.assertEquals('a_var.an_attr', self._find_primary(code, 10))
 
     def test_word_finder_on_word_beginning(self):
-        code = 'print a_var\n'
+        code = 'print(a_var)\n'
         word_finder = worder.Worder(code)
         result = word_finder.get_word_at(code.index('a_var'))
         self.assertEquals('a_var', result)
 
     def test_word_finder_on_primary_beginning(self):
-        code = 'print a_var\n'
+        code = 'print(a_var)\n'
         result = self._find_primary(code, code.index('a_var'))
         self.assertEquals('a_var', result)
 
     def test_word_finder_on_word_ending(self):
-        code = 'print a_var\n'
+        code = 'print(a_var)\n'
         word_finder = worder.Worder(code)
         result = word_finder.get_word_at(code.index('a_var') + 5)
         self.assertEquals('a_var', result)
 
     def test_word_finder_on_primary_ending(self):
-        code = 'print a_var\n'
+        code = 'print(a_var)\n'
         result = self._find_primary(code, code.index('a_var') + 5)
         self.assertEquals('a_var', result)
 
                           self._find_primary(code, 25))
 
     def test_dictionaries(self):
-        code = 'print {1: "one", 2: "two"}.keys()'
+        code = 'print({1: "one", 2: "two"}.keys())'
         self.assertEquals('{1: "one", 2: "two"}.keys',
                           self._find_primary(code, 29))
 
         name_finder.get_pyname_at(code.index('pass'))
 
     def test_one_liners(self):
-        code = 'var = 1\ndef f(): var = 2\nprint var\n'
+        code = 'var = 1\ndef f(): var = 2\nprint(var)\n'
         pymod = self.pycore.get_string_module(code)
         name_finder = rope.base.evaluate.ScopeNameFinder(pymod)
         pyname = name_finder.get_pyname_at(code.rindex('var'))
         self.assertEquals(pymod['var'], pyname)
 
     def test_one_liners_with_line_breaks(self):
-        code = 'var = 1\ndef f(\n): var = 2\nprint var\n'
+        code = 'var = 1\ndef f(\n): var = 2\nprint(var)\n'
         pymod = self.pycore.get_string_module(code)
         name_finder = rope.base.evaluate.ScopeNameFinder(pymod)
         pyname = name_finder.get_pyname_at(code.rindex('var'))
         self.assertEquals(pymod['var'], pyname)
 
     def test_one_liners_with_line_breaks2(self):
-        code = 'var = 1\ndef f(\np): var = 2\nprint var\n'
+        code = 'var = 1\ndef f(\np): var = 2\nprint(var)\n'
         pymod = self.pycore.get_string_module(code)
         name_finder = rope.base.evaluate.ScopeNameFinder(pymod)
         pyname = name_finder.get_pyname_at(code.rindex('var'))
         self.assertEquals((1, 3), line_finder.logical_line_in(2))
 
     def test_explicit_continuation(self):
-        code = 'print 2\na_var = (3 + \n    4, \n    5)\n'
+        code = 'print(2)\na_var = (3 + \n    4, \n    5)\n'
         line_finder = self._logical_finder(code)
         self.assertEquals((2, 4), line_finder.logical_line_in(2))
 
         self.assertEquals((1, 2), line_finder.logical_line_in(2))
 
     def test_fors_and_block_start(self):
-        code = 'l = range(10)\nfor i in l:\n    print i\n'
+        code = 'l = range(10)\nfor i in l:\n    print(i)\n'
         self.assertEquals(2, get_block_start(SourceLinesAdapter(code), 2))
 
     def test_problems_with_inner_indentations(self):

ropetest/contrib/codeassisttest.py

         proposals = sorted_proposals(result, typepref=['function'])
 
     def test_get_pydoc_unicode(self):
-        src = u'# coding: utf-8\ndef foo():\n  u"юникод-объект"'
+        src = '# coding: utf-8\ndef foo():\n  "юникод-объект"'
         doc = get_doc(self.project, src, src.index('foo') + 1)
-        self.assertTrue(isinstance(doc, unicode))
-        self.assertTrue(u'юникод-объект' in doc)
+        self.assertTrue(isinstance(doc, str))
+        self.assertTrue('юникод-объект' in doc)
 
     def test_get_pydoc_utf8_bytestring(self):
-        src = u'# coding: utf-8\ndef foo():\n  "байтстринг"'
+        src = '# coding: utf-8\ndef foo():\n  "байтстринг"'
         doc = get_doc(self.project, src, src.index('foo') + 1)
-        self.assertTrue(isinstance(doc, unicode))
-        self.assertTrue(u'байтстринг' in doc)
+        self.assertTrue(isinstance(doc, str))
+        self.assertTrue('байтстринг' in doc)
 
     def test_get_pydoc_for_functions(self):
         src = 'def a_func():\n' \

ropetest/objectinfertest.py

     def test_we_know_the_type_of_catched_exceptions(self):
         code = 'class MyError(Exception):\n    pass\n' \
                'try:\n    raise MyError()\n' \
-               'except MyError, e:\n    pass\n'
+               'except MyError as e:\n    pass\n'
         mod = self.pycore.get_string_module(
             code)
         my_error = mod['MyError'].get_object()
     def test_we_know_the_type_of_catched_multiple_excepts(self):
         code = 'class MyError(Exception):\n    pass\n' \
                'try:\n    raise MyError()\n' \
-               'except (MyError, Exception), e:\n    pass\n'
+               'except (MyError, Exception) as e:\n    pass\n'
         mod = self.pycore.get_string_module(
             code)
         my_error = mod['MyError'].get_object()

ropetest/projecttest.py

         src_folder = os.path.join(root, 'src')
         os.mkdir(src_folder)
         test_pyc = os.path.join(src_folder, 'test.pyc')
-        file(test_pyc, 'w').close()
+        open(test_pyc, 'w').close()
         for x in self.project.get_files():
             self.assertNotEquals('src/test.pyc', x.path)
 
 
     def test_file_encoding_reading(self):
         sample_file = self.project.root.create_file('my_file.txt')
-        contents = u'# -*- coding: utf-8 -*-\n#\N{LATIN SMALL LETTER I WITH DIAERESIS}\n'
-        file = open(sample_file.real_path, 'w')
+        contents = '# -*- coding: utf-8 -*-\n#\N{LATIN SMALL LETTER I WITH DIAERESIS}\n'
+        file = open(sample_file.real_path, 'wb')
         file.write(contents.encode('utf-8'))
         file.close()
         self.assertEquals(contents, sample_file.read())
 
     def test_file_encoding_writing(self):
         sample_file = self.project.root.create_file('my_file.txt')
-        contents = u'# -*- coding: utf-8 -*-\n\N{LATIN SMALL LETTER I WITH DIAERESIS}\n'
+        contents = '# -*- coding: utf-8 -*-\n\N{LATIN SMALL LETTER I WITH DIAERESIS}\n'
         sample_file.write(contents)
         self.assertEquals(contents, sample_file.read())
 
     def test_using_utf8_when_writing_in_case_of_errors(self):
         sample_file = self.project.root.create_file('my_file.txt')
-        contents = u'\n\N{LATIN SMALL LETTER I WITH DIAERESIS}\n'
+        contents = '\n\N{LATIN SMALL LETTER I WITH DIAERESIS}\n'
         sample_file.write(contents)
         self.assertEquals(contents, sample_file.read())
 
     def test_encoding_declaration_in_the_second_line(self):
         sample_file = self.project.root.create_file('my_file.txt')
-        contents = '\n# -*- coding: latin-1 -*-\n\xa9\n'
+        contents = b'\n# -*- coding: latin-1 -*-\n\xa9\n'
         file = open(sample_file.real_path, 'wb')
         file.write(contents)
         file.close()
 
     def test_read_bytes(self):
         sample_file = self.project.root.create_file('my_file.txt')
-        contents = '\n# -*- coding: latin-1 -*-\n\xa9\n'
+        contents = b'\n# -*- coding: latin-1 -*-\n\xa9\n'
         file = open(sample_file.real_path, 'wb')
         file.write(contents)
         file.close()
     # XXX: supporting utf_8_sig
     def xxx_test_file_encoding_reading_for_notepad_styles(self):
         sample_file = self.project.root.create_file('my_file.txt')
-        contents = u'#\N{LATIN SMALL LETTER I WITH DIAERESIS}\n'
+        contents = '#\N{LATIN SMALL LETTER I WITH DIAERESIS}\n'
         file = open(sample_file.real_path, 'w')
         # file.write('\xef\xbb\xbf')
         file.write(contents.encode('utf-8-sig'))
         sample_observer = _SampleObserver()
         self.project.add_observer(FilteredResourceObserver(sample_observer,
                                                            [my_file]))
-        file(my_file.real_path, 'w').close()
+        open(my_file.real_path, 'w').close()
         self.project.validate(root)
         self.assertEquals(my_file, sample_observer.last_created)
         self.assertEquals(1, sample_observer.change_count)
         sample_observer = _SampleObserver()
         self.project.add_observer(FilteredResourceObserver(sample_observer,
                                                            [my_file]))
-        file(my_file.real_path, 'w').close()
+        open(my_file.real_path, 'w').close()
         self.project.validate(root)
         self.project.validate(root)
         self.assertEquals(my_file, sample_observer.last_created)
 
     def test_simple_out_of_project_file(self):
         sample_file_path = os.path.join(self.test_directory, 'sample.txt')
-        sample_file = file(sample_file_path, 'w')
+        sample_file = open(sample_file_path, 'w')
         sample_file.write('sample content\n')
         sample_file.close()
         sample_resource = self.no_project.get_resource(sample_file_path)
         self.assertEquals([], sample_folder.get_children())
 
         sample_file_path = os.path.join(sample_folder_path, 'sample.txt')
-        file(sample_file_path, 'w').close()
+        open(sample_file_path, 'w').close()
         sample_resource = self.no_project.get_resource(sample_file_path)
         self.assertEquals(sample_resource, sample_folder.get_children()[0])
 
     def test_using_absolute_path(self):
         sample_file_path = os.path.join(self.test_directory, 'sample.txt')
-        file(sample_file_path, 'w').close()
+        open(sample_file_path, 'w').close()
         normal_sample_resource = self.no_project.get_resource(sample_file_path)
         absolute_sample_resource = \
             self.no_project.get_resource(os.path.abspath(sample_file_path))
         self.assertEquals([], sample_folder.get_children())
 
         sample_file_path = os.path.join(sample_folder_path, 'sample.txt')
-        file(sample_file_path, 'w').close()
+        open(sample_file_path, 'w').close()
         sample_resource = self.no_project.get_resource(sample_file_path)
         self.assertTrue(sample_folder.has_child('sample.txt'))
         self.assertFalse(sample_folder.has_child('doesnothave.txt'))
 
     def test_out_of_project_files_and_path_to_resource(self):
         sample_file_path = os.path.join(self.test_directory, 'sample.txt')
-        sample_file = file(sample_file_path, 'w')
+        sample_file = open(sample_file_path, 'w')
         sample_file.write('sample content\n')
         sample_file.close()
         sample_resource = self.no_project.get_resource(sample_file_path)

ropetest/pycoretest.py

         self.assertTrue('Project' in imported_module)
 
     def test_file_encoding_reading(self):
-        contents = u'# -*- coding: utf-8 -*-\n#\N{LATIN SMALL LETTER I WITH DIAERESIS}\n'
+        contents = '# -*- coding: utf-8 -*-\n#\N{LATIN SMALL LETTER I WITH DIAERESIS}\n'
         mod = testutils.create_module(self.project, 'mod')
         mod.write(contents)
         self.pycore.get_module('mod')
     def test_holding_error_location_information(self):
         try:
             mod = self.pycore.get_string_module('xyx print\n')
-        except exceptions.ModuleSyntaxError, e:
+        except exceptions.ModuleSyntaxError as e:
             self.assertEquals(1, e.lineno)
 
     def test_no_exceptions_on_module_encoding_problems(self):
         mod = testutils.create_module(self.project, 'mod')
         contents = '\nsdsdsd\n\xa9\n'
-        file = open(mod.real_path, 'wb')
+        file = open(mod.real_path, 'w')
         file.write(contents)
         file.close()
         mod.read()
     def test_syntax_errors_when_cannot_decode_file2(self):
         mod = testutils.create_module(self.project, 'mod')
         contents = '\n\xa9\n'
-        file = open(mod.real_path, 'wb')
+        file = open(mod.real_path, 'w')
         file.write(contents)
         file.close()
         self.pycore.resource_to_pyobject(mod)
     def test_syntax_errors_when_null_bytes(self):
         mod = testutils.create_module(self.project, 'mod')
         contents = '\n\x00\n'
-        file = open(mod.real_path, 'wb')
+        file = open(mod.real_path, 'w')
         file.write(contents)
         file.close()
         self.pycore.resource_to_pyobject(mod)
     def test_syntax_errors_when_bad_strs(self):
         mod = testutils.create_module(self.project, 'mod')
         contents = '\n"\\x0"\n'
-        file = open(mod.real_path, 'wb')
+        file = open(mod.real_path, 'w')
         file.write(contents)
         file.close()
         self.pycore.resource_to_pyobject(mod)

ropetest/refactor/extracttest.py

                'a = A()\n' \
                'def f():\n' \
                '    func = a.func()\n' \
-               '    print func\n'
+               '    print(func)\n'
 
         start, end = self._convert_line_range_to_offset(code, 6, 6)
         refactored = self.do_extract_method(code, start, end, 'g')
         refactored = refactored[refactored.index('A()') + 4:]
-        expected = 'def f():\n    func = g()\n    print func\n\n' \
-                   'def g():\n    func = a.func()\n    return func\n'
+        expected = 'def f():\n    func = g()\n    print(func)\n\n' \
+                   'def g():\n    func = a.func()\n    return(func)\n'
         self.assertEquals(expected, refactored)
 
     def test_global_option_for_extract_method(self):
         self.assertEquals(expected, refactored)
 
     def test_extracting_pieces_with_distinct_temp_names(self):
-        code = 'a = 1\nprint a\nb = 1\nprint b\n'
+        code = 'a = 1\nprint(a)\nb = 1\nprint(b)\n'
         start = code.index('a')
         end = code.index('\nb')
         refactored = self.do_extract_method(code, start, end, 'f',
                                             similar=True, global_=True)
-        expected = '\ndef f():\n    a = 1\n    print a\n\nf()\nf()\n'
+        expected = '\ndef f():\n    a = 1\n    print(a)\n\nf()\nf()\n'
         self.assertEquals(expected, refactored)
 
     def test_extracting_methods_in_global_functions_should_be_global(self):
         code = "def a_func(b):\n" \
                "    if b > 0:\n" \
                "        a = 2\n" \
-               "    print a\n"
+               "    print(a)\n"
         start, end = self._convert_line_range_to_offset(code, 2, 3)
         refactored = self.do_extract_method(code, start, end, 'extracted')
         expected = "def a_func(b):\n" \
                    "    a = extracted(b)\n" \
-                   "    print a\n\n" \
+                   "    print(a)\n\n" \
                    "def extracted(b):\n" \
                    "    if b > 0:\n" \
                    "        a = 2\n" \

ropetest/refactor/patchedasttest.py

                                          ',', ' ', 'Num', '', ','])
 
     def test_printnl_node(self):
-        source = 'print 1\n'
+        source = 'print(1)\n'
         ast = patchedast.get_patched_ast(source, True)
         checker = _ResultChecker(self, ast)
         checker.check_region('Print', 0, len(source) - 1)
                            '', ':', '\n    ', 'Pass'])
 
     def test_try_except_node(self):
-        source = 'try:\n    pass\nexcept Exception, e:\n    pass\n'
+        source = 'try:\n    pass\nexcept Exception as e:\n    pass\n'
         ast = patchedast.get_patched_ast(source, True)
         checker = _ResultChecker(self, ast)
         checker.check_children(
             if not isinstance(expected, (tuple, list)):
                 goals = [expected]
             for goal in goals:
-                if goal == '' or isinstance(child, basestring):
+                if goal == '' or isinstance(child, str):
                     self.test_case.assertEquals(goal, child)
                     break
             else:

ropetest/refactor/renametest.py

                           refactored.replace('\r\n', '\n'))
 
     def test_multi_byte_strs_and_renaming(self):
-        s = u'{LATIN SMALL LETTER I WITH DIAERESIS}' * 4
-        code = u'# -*- coding: utf-8 -*-\n# ' + s + \
+        s = '{LATIN SMALL LETTER I WITH DIAERESIS}' * 4
+        code = '# -*- coding: utf-8 -*-\n# ' + s + \
                 '\na = 1\nprint(2 + a + 2)\n'
         refactored = self._local_rename(code, code.rindex('a'), 'b')
-        self.assertEquals(u'# -*- coding: utf-8 -*-\n# ' + s +
+        self.assertEquals('# -*- coding: utf-8 -*-\n# ' + s +
                           '\nb = 1\nprint(2 + b + 2)\n', refactored)
 
     def test_resources_parameter(self):

ropetest/runmodtest.py

         file_path = 'sample.py'
         self.make_sample_python_file(file_path,
                                      "def get_text():" +
-                                     "\n    print 'output text'\n    return 'run'\n")
+                                     "\n    print('output text')\n    return 'run'\n")
         temp_file_name = 'processtest.tmp'
         try:
             file_resource = self.project.get_resource(file_path)

ropetest/testutils.py

           for i in range(12):
             try:
                 _remove_recursively(path)
-            except OSError, e:
+            except OSError as e:
                 if e.errno not in (13, 16, 32):
                     raise
                 time.sleep(0.3)
     end = lines.index('Getting Started')
     return '\n' + '\n'.join(lines[:end]) + '\n'
 
-setup(name='rope',
+setup(name='rope_py3k',
       version=rope.VERSION,
       description='a python refactoring library...',
       long_description=get_long_description(),
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.