Skip to content

Commit

Permalink
sagemathgh-36874: ruff and pep E275 fixes in misc
Browse files Browse the repository at this point in the history
    
Some fixes performed by `ruff` in the `misc` folder.

Also manually fixing some pycodestyle E275

Also adding a few links for errors in the doc

### 📝 Checklist

- [x] The title is concise, informative, and self-explanatory.
- [x] The description explains in detail what this PR is about.
    
URL: sagemath#36874
Reported by: Frédéric Chapoton
Reviewer(s): Matthias Köppe
  • Loading branch information
Release Manager committed Dec 22, 2023
2 parents 4c656cc + 00b3ef1 commit 3618281
Show file tree
Hide file tree
Showing 22 changed files with 58 additions and 68 deletions.
4 changes: 2 additions & 2 deletions src/sage/misc/abstract_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def abstract_method(f=None, optional=False):
sage: A.my_method
<abstract method my_method at ...>
The current policy is that a ``NotImplementedError`` is raised
The current policy is that a :class:`NotImplementedError` is raised
when accessing the method through an instance, even before the
method is called::
Expand Down Expand Up @@ -193,7 +193,7 @@ def _sage_src_lines_(self):
sage: src[0]
'def version():\n'
sage: lines
19
18
"""
from sage.misc.sageinspect import sage_getsourcelines
return sage_getsourcelines(self._f)
Expand Down
23 changes: 11 additions & 12 deletions src/sage/misc/banner.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
r"""
SageMath version and banner info
"""
Expand Down Expand Up @@ -58,14 +57,14 @@ def banner_text(full=True):
if not full:
return version()

bars = u"─" * 68
bars = "─" * 68
s = []
a = s.append
a(u'┌' + bars + u'┐')
a(u"\n│ %-66s │\n" % version())
a('┌' + bars + '┐')
a("\n│ %-66s │\n" % version())
python_version = sys.version_info[:3]
a(u"│ %-66s │\n" % 'Using Python {}.{}.{}. Type "help()" for help.'.format(*python_version))
a(u'└' + bars + u'┘')
a("│ %-66s │\n" % 'Using Python {}.{}.{}. Type "help()" for help.'.format(*python_version))
a('└' + bars + '┘')
pre = version_dict()['prerelease']
try:
import sage.all
Expand All @@ -75,15 +74,15 @@ def banner_text(full=True):
if pre or not have_sage_all:
red_in = '\033[31m'
red_out = '\033[0m'
bars2 = bars.replace(u'─', u'━')
bars2 = bars.replace('─', '━')
a('\n')
a(red_in + u'┏' + bars2 + u'┓' + '\n')
a(red_in + '┏' + bars2 + '┓' + '\n')
if pre:
a(u"┃ %-66s ┃\n" % 'Warning: this is a prerelease version, and it may be unstable.')
a("┃ %-66s ┃\n" % 'Warning: this is a prerelease version, and it may be unstable.')
if not have_sage_all:
a(u"┃ %-66s ┃\n" % 'Warning: sage.all is not available; this is a limited REPL.')
a(u'┗' + bars2 + u'┛' + red_out)
return u''.join(s)
a("┃ %-66s ┃\n" % 'Warning: sage.all is not available; this is a limited REPL.')
a('┗' + bars2 + '┛' + red_out)
return ''.join(s)


def banner():
Expand Down
1 change: 0 additions & 1 deletion src/sage/misc/call.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Attribute and method calling
"""
Expand Down
1 change: 0 additions & 1 deletion src/sage/misc/converting_dict.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
r"""
Converting Dictionary
Expand Down
2 changes: 1 addition & 1 deletion src/sage/misc/cython.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ def cython(filename, verbose=0, compile_message=False,
try:
with open(name + ".lis") as f:
cython_messages = f.read()
except IOError:
except OSError:
cython_messages = "Error compiling Cython file"
except CompileError:
raise RuntimeError(cython_messages.strip())
Expand Down
10 changes: 5 additions & 5 deletions src/sage/misc/edit_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def template_fields(template):
"""
dict = {}
dummy = None
while not(dummy):
while not dummy:
try:
dummy = template.substitute(dict)
except KeyError as inst:
Expand Down Expand Up @@ -168,10 +168,10 @@ def set_edit_template(template_string):
"""
global edit_template

if not(isinstance(template_string, Template)):
if not isinstance(template_string, Template):
template_string = Template(template_string)
fields = set(template_fields(template_string))
if not(fields <= set(['file', 'line']) and ('file' in fields)):
if not (fields <= set(['file', 'line']) and ('file' in fields)):
raise ValueError("Only ${file} and ${line} are allowed as template variables, and ${file} must occur.")
edit_template = template_string

Expand Down Expand Up @@ -253,7 +253,7 @@ def edit(obj, editor=None, bg=None):

if editor:
set_editor(editor)
elif not(edit_template):
elif not edit_template:
try:
ED = os.environ['EDITOR']
EDITOR = ED.split()
Expand All @@ -263,7 +263,7 @@ def edit(obj, editor=None, bg=None):
except (ValueError, KeyError, IndexError):
raise ValueError("Use set_edit_template(<template_string>) to set a default")

if not(edit_template):
if not edit_template:
raise ValueError("Use set_edit_template(<template_string>) to set a default")

filename, lineno = file_and_line(obj)
Expand Down
3 changes: 1 addition & 2 deletions src/sage/misc/element_with_label.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
r"""
Elements with labels.
Expand Down Expand Up @@ -170,4 +169,4 @@ def __ne__(self, other):
sage: a != x
False
"""
return not(self == other)
return not (self == other)
18 changes: 9 additions & 9 deletions src/sage/misc/explain_pickle.py
Original file line number Diff line number Diff line change
Expand Up @@ -461,8 +461,8 @@ def run_pickle(self, p):
sage: sib(pe.run_pickle('T\5\0\0\0hello.')) # py2
{atomic:'hello'}
"""
for (op, arg, pos) in genops(p):
assert(not(self.stopped))
for op, arg, pos in genops(p):
assert not self.stopped
try:
handler = getattr(self, op.name)
except AttributeError:
Expand All @@ -472,8 +472,8 @@ def run_pickle(self, p):
else:
handler(arg)

assert(self.stopped)
assert(len(self.stack) == 1)
assert self.stopped
assert len(self.stack) == 1
return self.stack[0]

def check_value(self, v):
Expand All @@ -493,7 +493,7 @@ def check_value(self, v):
AssertionError
sage: pe.check_value(sib(7))
"""
assert(isinstance(v, (SageInputExpression, PickleObject)))
assert isinstance(v, (SageInputExpression, PickleObject))

def push(self, v):
r"""
Expand Down Expand Up @@ -2442,13 +2442,13 @@ def unpickle_build(obj, state):
slots = None

if state is not None:
assert(isinstance(state, dict))
assert isinstance(state, dict)
d = obj.__dict__
for k, v in state.items():
d[k] = v

if slots is not None:
assert(isinstance(slots, dict))
assert isinstance(slots, dict)
for k, v in slots.items():
setattr(obj, k, v)

Expand Down Expand Up @@ -2635,11 +2635,11 @@ def pers_load(s):
if cpickle_ok:
cpickle_repr = repr(cpickle_res)

assert(current_repr == generic_repr == cpickle_repr)
assert current_repr == generic_repr == cpickle_repr

print("result: " + current_repr)
else:
assert(current_repr == generic_repr)
assert current_repr == generic_repr
print("result: " + current_repr + " (cPickle raised an exception!)")


Expand Down
1 change: 0 additions & 1 deletion src/sage/misc/functional.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Functional notation
Expand Down
2 changes: 1 addition & 1 deletion src/sage/misc/latex.py
Original file line number Diff line number Diff line change
Expand Up @@ -806,7 +806,7 @@ def subpcall(x):
try:
with open(base + '/' + filename + '.log') as f:
print(f.read())
except IOError:
except OSError:
pass
return "Error latexing slide."
return return_suffix
Expand Down
1 change: 0 additions & 1 deletion src/sage/misc/latex_standalone.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
r"""
Standalone LaTeX Document class and TikzPicture
Expand Down
8 changes: 4 additions & 4 deletions src/sage/misc/lazy_attribute.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ cdef class _lazy_attribute():

def _sage_src_lines_(self):
r"""
Returns the source code location for the wrapped function.
Return the source code location for the wrapped function.
EXAMPLES::
Expand All @@ -87,15 +87,14 @@ cdef class _lazy_attribute():
sage: src[0]
'def banner():\n'
sage: lines
89
88
"""
from sage.misc.sageinspect import sage_getsourcelines
return sage_getsourcelines(self.f)


def __get__(self, a, cls):
"""
Implements the attribute access protocol.
Implement the attribute access protocol.
EXAMPLES::
Expand Down Expand Up @@ -143,6 +142,7 @@ cdef class _lazy_attribute():
raise
return result


class lazy_attribute(_lazy_attribute):
r"""
A lazy attribute for an object is like a usual attribute, except
Expand Down
4 changes: 2 additions & 2 deletions src/sage/misc/mrange.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,8 +336,8 @@ def __len__(self):
"""
Return the cardinality of this iterator as an int.
Raises a ``TypeError`` if the cardinality does not fit into a Python
int.
This raises a :class:`TypeError` if the cardinality does not fit
into a Python int.
EXAMPLES::
Expand Down
2 changes: 1 addition & 1 deletion src/sage/misc/package.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def spkg_type(name):
return None
try:
f = open(os.path.join(SAGE_PKGS, name, "type"))
except IOError:
except OSError:
# Probably an empty directory => ignore
return None

Expand Down
2 changes: 1 addition & 1 deletion src/sage/misc/package_dir.py
Original file line number Diff line number Diff line change
Expand Up @@ -615,7 +615,7 @@ def handle_file(root, file):
if package in ordinary_packages:
pass
elif ((missing_all_files := distributions_per_directives - package_distributions_per_all_files[package])
and not(missing_all_files == set(['']) and len(distributions_per_directives) < 2)):
and not (missing_all_files == set(['']) and len(distributions_per_directives) < 2)):
s = '' if len(missing_all_files) == 1 else 's'
print(f'{package}: missing file{s} ' + ', '.join(_all_filename(distribution)
for distribution in missing_all_files))
4 changes: 2 additions & 2 deletions src/sage/misc/random_testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ def test_add_commutes(trials, verbose=False):
b = QQ.random_element()
if verbose:
print("a == {}, b == {} ...".format(a, b))
assert(a + b == b + a)
assert a + b == b + a
if verbose:
print("Passes!")

Expand Down Expand Up @@ -258,6 +258,6 @@ def test_add_is_mul(trials, verbose=False):
b = QQ.random_element()
if verbose:
print("a == {}, b == {} ...".format(a, b))
assert(a + b == a * b)
assert a + b == a * b
if verbose:
print("Passes!")
6 changes: 3 additions & 3 deletions src/sage/misc/sage_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -3475,11 +3475,11 @@ def verify_same(a, b):
"""
from sage.structure.element import is_Element
if is_Element(a):
assert(a.parent() == b.parent())
assert a.parent() == b.parent()
else:
assert(type(a) is type(b))
assert type(a) is type(b)
if isinstance(a, (RealIntervalFieldElement, ComplexIntervalFieldElement)):
assert(a.endpoints() == b.endpoints()), "Expected %s == %s" % (a, b)
assert a.endpoints() == b.endpoints(), "Expected %s == %s" % (a, b)
return

if not (a == b):
Expand Down
7 changes: 3 additions & 4 deletions src/sage/misc/sage_timeit.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Accurate timing information for Sage commands
Expand Down Expand Up @@ -90,9 +89,9 @@ def __repr__(self):
1 loop, best of 2: 3.14 ns per loop
"""
if self.stats[0] > 1:
s = u"%d loops, best of %d: %.*g %s per loop" % self.stats
s = "%d loops, best of %d: %.*g %s per loop" % self.stats
else:
s = u"%d loop, best of %d: %.*g %s per loop" % self.stats
s = "%d loop, best of %d: %.*g %s per loop" % self.stats

if isinstance(s, str):
return s
Expand Down Expand Up @@ -217,7 +216,7 @@ def sage_timeit(stmt, globals_dict=None, preparse=None, number=0, repeat=3, prec
if stmt == "":
return ''

units = [u"s", u"ms", u"μs", u"ns"]
units = ["s", "ms", "μs", "ns"]
scaling = [1, 1e3, 1e6, 1e9]

timer = timeit_.Timer()
Expand Down
Loading

0 comments on commit 3618281

Please sign in to comment.