Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix some python2-isms #555

Merged
merged 4 commits into from Nov 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion rope/base/change.py
Expand Up @@ -105,7 +105,7 @@ def __str__(self):
else:
string_date = date.strftime("%d %b, %Y")
string_time = date.strftime("%H:%M:%S")
string_time = "{} {} ".format(string_date, string_time)
string_time = f"{string_date} {string_time} "
return self.description + " - " + string_time
return self.description

Expand Down
4 changes: 2 additions & 2 deletions rope/base/exceptions.py
Expand Up @@ -47,7 +47,7 @@ def __init__(self, filename, lineno, message):
self.lineno = lineno
self.message_ = message
super().__init__(
"Syntax error in file <{}> line <{}>: {}".format(filename, lineno, message)
f"Syntax error in file <{filename}> line <{lineno}>: {message}"
)


Expand All @@ -57,4 +57,4 @@ class ModuleDecodeError(RopeError):
def __init__(self, filename, message):
self.filename = filename
self.message_ = message
super().__init__("Cannot decode file <{}>: {}".format(filename, message))
super().__init__(f"Cannot decode file <{filename}>: {message}")
2 changes: 1 addition & 1 deletion rope/base/oi/type_hinting/evaluate.py
Expand Up @@ -26,7 +26,7 @@ def evaluate(self, pyobject):

def __repr__(self):
if self.name == "(name)":
return "({} {})".format(self.name[1:-1], self.value)
return f"({self.name[1:-1]} {self.value})"
out = [repr(self.name), self.first, self.second, self.third]
out = [str(i) for i in out if i]
return "(" + " ".join(out) + ")"
Expand Down
2 changes: 1 addition & 1 deletion rope/base/resources.py
Expand Up @@ -55,7 +55,7 @@ def move(self, new_location):
"""Move resource to `new_location`"""
self._perform_change(
change.MoveResource(self, new_location),
"Moving <{}> to <{}>".format(self.path, new_location),
f"Moving <{self.path}> to <{new_location}>",
)

def remove(self):
Expand Down
9 changes: 3 additions & 6 deletions rope/base/utils/datastructures.py
@@ -1,10 +1,7 @@
# this snippet was taken from this link
# http://code.activestate.com/recipes/576694/

try:
from collections.abc import MutableSet
except ImportError:
from collections import MutableSet
from collections.abc import MutableSet


class OrderedSet(MutableSet):
Expand Down Expand Up @@ -60,8 +57,8 @@ def pop(self, last=True):

def __repr__(self):
if not self:
return "{}()".format(self.__class__.__name__)
return "{}({!r})".format(self.__class__.__name__, list(self))
return f"{self.__class__.__name__}()"
return f"{self.__class__.__name__}({list(self)!r})"

def __eq__(self, other):
if isinstance(other, OrderedSet):
Expand Down
2 changes: 1 addition & 1 deletion rope/contrib/codeassist.py
Expand Up @@ -238,7 +238,7 @@ def __init__(self, name, scope, pyname=None):
self.scope = self._get_scope(scope)

def __str__(self):
return "{} ({}, {})".format(self.name, self.scope, self.type)
return f"{self.name} ({self.scope}, {self.type})"

def __repr__(self):
return str(self)
Expand Down
2 changes: 1 addition & 1 deletion rope/contrib/finderrors.py
Expand Up @@ -87,4 +87,4 @@ def __init__(self, lineno, error):
self.error = error

def __str__(self):
return "{}: {}".format(self.lineno, self.error)
return f"{self.lineno}: {self.error}"
2 changes: 1 addition & 1 deletion rope/contrib/fixsyntax.py
Expand Up @@ -33,7 +33,7 @@ def get_pymodule(self):
)
except exceptions.ModuleSyntaxError as e:
if msg is None:
msg = "{}:{} {}".format(e.filename, e.lineno, e.message_)
msg = f"{e.filename}:{e.lineno} {e.message_}"
if tries < self.maxfixes:
tries += 1
self.commenter.comment(e.lineno)
Expand Down
8 changes: 3 additions & 5 deletions rope/contrib/generate.py
Expand Up @@ -62,9 +62,7 @@ def _check_exceptional_conditions(self):
)

def get_changes(self):
changes = change.ChangeSet(
"Generate {} <{}>".format(self._get_element_kind(), self.name)
)
changes = change.ChangeSet(f"Generate {self._get_element_kind()} <{self.name}>")
indents = self.info.get_scope_indents()
blanks = self.info.get_blank_lines()
base_definition = sourceutils.fix_indentation(self._get_element(), indents)
Expand Down Expand Up @@ -140,7 +138,7 @@ class GenerateModule(_Generate):
def get_changes(self):
package = self.info.get_package()
changes = change.ChangeSet("Generate Module <%s>" % self.name)
new_resource = self.project.get_file("{}/{}.py".format(package.path, self.name))
new_resource = self.project.get_file(f"{package.path}/{self.name}.py")
if new_resource.exists():
raise exceptions.RefactoringError(
"Module <%s> already exists" % new_resource.path
Expand All @@ -160,7 +158,7 @@ class GeneratePackage(_Generate):
def get_changes(self):
package = self.info.get_package()
changes = change.ChangeSet("Generate Package <%s>" % self.name)
new_resource = self.project.get_folder("{}/{}".format(package.path, self.name))
new_resource = self.project.get_folder(f"{package.path}/{self.name}")
if new_resource.exists():
raise exceptions.RefactoringError(
"Package <%s> already exists" % new_resource.path
Expand Down
8 changes: 2 additions & 6 deletions rope/refactor/encapsulate_field.py
Expand Up @@ -105,12 +105,8 @@ def _change_holding_module(self, changes, renamer, getter, setter):
class_scope.get_start()
)
indents = sourceutils.get_indent(self.project) * " "
getter = "def {}(self):\n{}return self.{}".format(getter, indents, self.name)
setter = "def {}(self, value):\n{}self.{} = value".format(
setter,
indents,
self.name,
)
getter = f"def {getter}(self):\n{indents}return self.{self.name}"
setter = f"def {setter}(self, value):\n{indents}self.{self.name} = value"
new_source = sourceutils.add_methods(pymodule, class_scope, [getter, setter])
return new_source

Expand Down
2 changes: 1 addition & 1 deletion rope/refactor/extract.py
Expand Up @@ -80,7 +80,7 @@ def get_changes(self, extracted_name, similar=False, global_=False, kind=None):
)
info.kind = self._get_kind(kind)
new_contents = _ExtractPerformer(info).extract()
changes = ChangeSet("Extract {} <{}>".format(info.kind, extracted_name))
changes = ChangeSet(f"Extract {info.kind} <{extracted_name}>")
changes.add_change(ChangeContents(self.resource, new_contents))
return changes

Expand Down
8 changes: 3 additions & 5 deletions rope/refactor/functionutils.py
Expand Up @@ -15,13 +15,13 @@ def __init__(
self.keywords_arg = keywords_arg

def to_string(self):
return "{}({})".format(self.function_name, self.arguments_to_string())
return f"{self.function_name}({self.arguments_to_string()})"

def arguments_to_string(self, from_index=0):
params = []
for arg, default in self.args_with_defaults:
if default is not None:
params.append("{}={}".format(arg, default))
params.append(f"{arg}={default}")
else:
params.append(arg)
if self.args_arg is not None:
Expand Down Expand Up @@ -98,9 +98,7 @@ def to_string(self):
if self.args[start:]:
params.extend(self.args[start:])
if self.keywords:
params.extend(
["{}={}".format(name, value) for name, value in self.keywords]
)
params.extend([f"{name}={value}" for name, value in self.keywords])
if self.args_arg is not None:
params.append("*" + self.args_arg)
if self.keywords_arg:
Expand Down
2 changes: 1 addition & 1 deletion rope/refactor/introduce_factory.py
Expand Up @@ -117,7 +117,7 @@ def _get_factory_method(self, lines, class_scope, factory_name, global_):
)
unindented_factory = (
"@staticmethod\ndef %s(*args, **kwds):\n" % factory_name
+ "{}return {}(*args, **kwds)\n".format(unit_indents, self.old_name)
+ f"{unit_indents}return {self.old_name}(*args, **kwds)\n"
)
indents = self._get_scope_indents(lines, class_scope) + sourceutils.get_indent(
self.project
Expand Down
4 changes: 2 additions & 2 deletions rope/refactor/method_object.py
Expand Up @@ -88,9 +88,9 @@ def _get_init(self):
if arg == "self":
new_name = "host"
header += ", %s" % new_name
body += indents * 2 + "self.{} = {}\n".format(arg, new_name)
body += indents * 2 + f"self.{arg} = {new_name}\n"
header += "):"
return "{}\n{}\n".format(header, body)
return f"{header}\n{body}\n"

def _get_parameter_names(self):
return self.pyfunction.get_param_names()
2 changes: 1 addition & 1 deletion rope/refactor/patchedast.py
Expand Up @@ -924,7 +924,7 @@ def consume(self, token, skip_comment=True):
self._skip_comment()
except (ValueError, TypeError) as e:
raise MismatchedTokenError(
"Token <{}> at {} cannot be matched".format(token, self._get_location())
f"Token <{token}> at {self._get_location()} cannot be matched"
)
self.offset = new_offset + len(token)
return (new_offset, self.offset)
Expand Down
6 changes: 2 additions & 4 deletions rope/refactor/rename.py
Expand Up @@ -105,7 +105,7 @@ def unsure_func(value=unsure):
resources = [self.resource]
if resources is None:
resources = self.project.get_python_files()
changes = ChangeSet("Renaming <{}> to <{}>".format(self.old_name, new_name))
changes = ChangeSet(f"Renaming <{self.old_name}> to <{new_name}>")
finder = occurrences.create_finder(
self.project,
self.old_name,
Expand Down Expand Up @@ -189,9 +189,7 @@ def _get_scope_offset(self):
return scope.get_region()

def get_changes(self, new_name, only_calls=False, reads=True, writes=True):
changes = ChangeSet(
"Changing <{}> occurrences to <{}>".format(self.old_name, new_name)
)
changes = ChangeSet(f"Changing <{self.old_name}> occurrences to <{new_name}>")
scope_start, scope_end = self._get_scope_offset()
finder = occurrences.create_finder(
self.project,
Expand Down
4 changes: 1 addition & 3 deletions rope/refactor/restructure.py
Expand Up @@ -136,9 +136,7 @@ def get_changes(
stacklevel=2,
)
self.imports = imports
changes = change.ChangeSet(
"Restructuring <{}> to <{}>".format(self.pattern, self.goal)
)
changes = change.ChangeSet(f"Restructuring <{self.pattern}> to <{self.goal}>")
if resources is not None:
files = [
resource
Expand Down
48 changes: 0 additions & 48 deletions ropetest/__init__.py
@@ -1,48 +0,0 @@
import sys

import unittest

import ropetest.projecttest
import ropetest.codeanalyzetest
import ropetest.doatest
import ropetest.type_hinting_test
import ropetest.pycoretest
import ropetest.pyscopestest
import ropetest.objectinfertest
import ropetest.objectdbtest
import ropetest.advanced_oi_test
import ropetest.runmodtest
import ropetest.builtinstest
import ropetest.historytest
import ropetest.simplifytest

import ropetest.contrib
import ropetest.refactor


def suite():
result = unittest.TestSuite()
result.addTests(ropetest.projecttest.suite())
result.addTests(ropetest.codeanalyzetest.suite())
result.addTests(ropetest.doatest.suite())
result.addTests(ropetest.type_hinting_test.suite())
result.addTests(ropetest.pycoretest.suite())
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.runmodtest.suite())
result.addTests(ropetest.builtinstest.suite())
result.addTests(ropetest.historytest.suite())
result.addTests(ropetest.simplifytest.suite())

result.addTests(ropetest.refactor.suite())
result.addTests(ropetest.contrib.suite())

return result


if __name__ == "__main__":
runner = unittest.TextTestRunner()
result = runner.run(suite())
sys.exit(not result.wasSuccessful())
33 changes: 0 additions & 33 deletions ropetest/contrib/__init__.py
@@ -1,33 +0,0 @@
import sys

import unittest

import ropetest.contrib.autoimporttest
import ropetest.contrib.changestacktest
import ropetest.contrib.codeassisttest
import ropetest.contrib.finderrorstest
import ropetest.contrib.findittest
import ropetest.contrib.fixmodnamestest
import ropetest.contrib.generatetest


def suite():
result = unittest.TestSuite()
result.addTests(unittest.makeSuite(ropetest.contrib.generatetest.GenerateTest))
result.addTests(ropetest.contrib.codeassisttest.suite())
result.addTests(ropetest.contrib.autoimporttest.suite())
result.addTests(ropetest.contrib.findittest.suite())
result.addTests(
unittest.makeSuite(ropetest.contrib.changestacktest.ChangeStackTest)
)
result.addTests(
unittest.makeSuite(ropetest.contrib.fixmodnamestest.FixModuleNamesTest)
)
result.addTests(unittest.makeSuite(ropetest.contrib.finderrorstest.FindErrorsTest))
return result


if __name__ == "__main__":
runner = unittest.TextTestRunner()
result = runner.run(suite())
sys.exit(not result.wasSuccessful())
2 changes: 1 addition & 1 deletion ropetest/refactor/movetest.py
Expand Up @@ -1184,7 +1184,7 @@ def f(): pass
self.mod2.write(code2)
mover = move.create_move(self.project, self.mod2, code2.index("f()") + 1)
self.project.do(mover.get_changes(self.mod1))
expected = "%s\n%s" % (code1, code2)
expected = f"{code1}\n{code2}"
self.assertEqual(expected, self.mod1.read())

def test_moving_decorated_function(self):
Expand Down
6 changes: 3 additions & 3 deletions ropetest/testutils.py
Expand Up @@ -81,23 +81,23 @@ def only_for(version):
"""Should be used as a decorator for a unittest.TestCase test method"""
return unittest.skipIf(
sys.version_info < parse_version(version),
"This test requires at least {0} version of Python.".format(version),
f"This test requires at least {version} version of Python.",
)


def only_for_versions_lower(version):
"""Should be used as a decorator for a unittest.TestCase test method"""
return unittest.skipIf(
sys.version_info > parse_version(version),
"This test requires version of Python lower than {0}".format(version),
f"This test requires version of Python lower than {version}",
)


def only_for_versions_higher(version):
"""Should be used as a decorator for a unittest.TestCase test method"""
return unittest.skipIf(
sys.version_info < parse_version(version),
"This test requires version of Python higher than {0}".format(version),
f"This test requires version of Python higher than {version}",
)


Expand Down