Skip to content

Commit

Permalink
sagemathgh-38740: fixing some suggestions by ruff
Browse files Browse the repository at this point in the history
    
some by hand, some scripted

in particular, removal of useless parentheses

### 📝 Checklist

- [x] The title is concise and informative.
- [x] The description explains in detail what this PR is about.
- [ ] I have linked a relevant issue or discussion.
- [ ] I have created tests covering the changes.
- [ ] I have updated the documentation and checked the documentation
preview.
    
URL: sagemath#38740
Reported by: Frédéric Chapoton
Reviewer(s): Frédéric Chapoton, Kwankyu Lee
  • Loading branch information
Release Manager committed Oct 18, 2024
2 parents dff16e5 + a5489f7 commit 3f58180
Show file tree
Hide file tree
Showing 94 changed files with 196 additions and 205 deletions.
10 changes: 5 additions & 5 deletions src/sage/categories/examples/commutative_additive_semigroups.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,11 +166,10 @@ def __init__(self, parent, iterable):
{'a': 2, 'b': 0, 'c': 1, 'd': 5}
"""
d = {a: 0 for a in parent.alphabet}
for a, c in iterable:
d[a] = c
d.update(iterable)
ElementWrapper.__init__(self, parent, d)

def _repr_(self):
def _repr_(self) -> str:
"""
EXAMPLES::
Expand All @@ -182,8 +181,9 @@ def _repr_(self):
0
"""
d = self.value
result = ' + '.join( ("%s*%s" % (d[a],a) if d[a] != 1 else a) for a in sorted(d.keys()) if d[a] != 0)
return '0' if result == '' else result
result = ' + '.join(("%s*%s" % (d[a], a) if d[a] != 1 else a)
for a in sorted(d.keys()) if d[a] != 0)
return '0' if not result else result

def __hash__(self):
"""
Expand Down
8 changes: 3 additions & 5 deletions src/sage/categories/pushout.py
Original file line number Diff line number Diff line change
Expand Up @@ -3055,13 +3055,11 @@ def merge(self, other):
codomain = self.codomain().join([self.codomain(), other.codomain()])
# Get the optional arguments:
as_field = self.as_field or other.as_field
kwds = {}
for k,v in self.kwds.items():
kwds[k] = v
for k,v in other.kwds.items():
kwds = dict(self.kwds)
for k, v in other.kwds.items():
if k == 'category':
if kwds[k] is not None:
kwds[k] = v.join([v,kwds[k]])
kwds[k] = v.join([v, kwds[k]])
else:
kwds[k] = v
continue
Expand Down
2 changes: 1 addition & 1 deletion src/sage/coding/code_bounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -737,7 +737,7 @@ def elias_bound_asymp(delta, q):
0.39912396330...
"""
r = 1 - 1 / q
return RDF((1-entropy(r-sqrt(r*(r-delta)), q)))
return RDF(1-entropy(r-sqrt(r*(r-delta)), q))


def mrrw1_bound_asymp(delta, q):
Expand Down
2 changes: 1 addition & 1 deletion src/sage/coding/source_coding/huffman.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ def encode(self, string):
'Sage is my most favorite general purpose computer algebra system'
"""
if self._character_to_code:
return "".join((self._character_to_code[x] for x in string))
return "".join(self._character_to_code[x] for x in string)

def decode(self, string):
r"""
Expand Down
3 changes: 1 addition & 2 deletions src/sage/combinat/interval_posets.py
Original file line number Diff line number Diff line change
Expand Up @@ -3533,8 +3533,7 @@ def profil(gr, vertex):

liste = clockwise_labelling(graph0, -1)[1:]
relabelling = {l: i for i, l in enumerate(liste)}
for l in [-1, -2, -3]:
relabelling[l] = l
relabelling.update((i, i) for i in [-1, -2, -3])
new_graph = graph.relabel(relabelling, inplace=False)

dyckword_top = []
Expand Down
2 changes: 1 addition & 1 deletion src/sage/combinat/root_system/type_reducible.py
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,7 @@ def inject_weights(self, i, v):
[(1, 1, 0, 0, 0), (0, 0, 0, 1/2, 1/2)]
"""
shift = self.root_system.cartan_type()._shifts[i]
return self._from_dict( dict([(shift+k, c) for (k,c) in v ]))
return self._from_dict({shift + k: c for k, c in v})

@cached_method
def simple_root(self, i):
Expand Down
2 changes: 1 addition & 1 deletion src/sage/combinat/sf/sfa.py
Original file line number Diff line number Diff line change
Expand Up @@ -1982,7 +1982,7 @@ def _change_by_plethysm(self, x, expr, deg_one):
# Convert to the power sum
p = self.realization_of().power()
p_x = p(x)
expr_k = lambda k: expr.subs(**dict([(str(x),x**k) for x in deg_one]))
expr_k = lambda k: expr.subs(**{str(x): x**k for x in deg_one})
f = lambda m,c: (m, c*prod([expr_k(k) for k in m]))
return self(p_x.map_item(f))

Expand Down
32 changes: 16 additions & 16 deletions src/sage/crypto/mq/rijndael_gf.py
Original file line number Diff line number Diff line change
Expand Up @@ -613,8 +613,8 @@ def __call__(self, text, key, algorithm='encrypt', format='hex'):
elif algorithm == 'decrypt':
return self.decrypt(text, key, format)
else:
raise ValueError(("keyword 'algorithm' must be either 'encrypt' "
"or 'decrypt'"))
raise ValueError("keyword 'algorithm' must be either 'encrypt' "
"or 'decrypt'")

def __repr__(self):
r"""
Expand Down Expand Up @@ -981,8 +981,8 @@ def encrypt(self, plain, key, format='hex'):
key_state = self._bin_to_GF(key)
roundKeys = self.expand_key(key_state)
else:
raise ValueError(("'format' keyword must be either 'hex' or "
"'binary'"))
raise ValueError("'format' keyword must be either 'hex' or "
"'binary'")

state = self.add_round_key(state, roundKeys[0])
for r in range(self._Nr-1):
Expand Down Expand Up @@ -1057,8 +1057,8 @@ def decrypt(self, ciphertext, key, format='hex'):
elif format == 'binary':
if not isinstance(ciphertext, str) or \
any(c not in '01' for c in ciphertext):
raise TypeError(("'ciphertext' keyword must be a binary "
"string"))
raise TypeError("'ciphertext' keyword must be a binary "
"string")
if len(ciphertext) != 32 * self._Nb:
msg = "'ciphertext' keyword's length must be {0}, not {1}"
raise ValueError(msg.format(32 * self._Nb, len(ciphertext)))
Expand All @@ -1072,8 +1072,8 @@ def decrypt(self, ciphertext, key, format='hex'):
key_state = self._bin_to_GF(key)
roundKeys = self.expand_key(key_state)
else:
raise ValueError(("'format' keyword must be either \'hex\' or "
"'binary'"))
raise ValueError("'format' keyword must be either \'hex\' or "
"'binary'")

state = self.add_round_key(state, roundKeys[self._Nr])
state = self.shift_rows(state, algorithm='decrypt')
Expand Down Expand Up @@ -1874,8 +1874,8 @@ def _sub_bytes_pc(self, row, col, algorithm='encrypt', no_inversion=False):
else:
return result ** 254
else:
raise ValueError(("keyword 'algorithm' must be either 'encrypt' "
"or 'decrypt'"))
raise ValueError("keyword 'algorithm' must be either 'encrypt' "
"or 'decrypt'")

def _srd(self, el, algorithm='encrypt'):
r"""
Expand Down Expand Up @@ -1910,8 +1910,8 @@ def _srd(self, el, algorithm='encrypt'):
state = [el] + [self._F.zero()]*((4 * self._Nb)-1)
return p(state) ** 254
else:
raise ValueError(("keyword 'algorithm' must be either 'encrypt' "
"or 'decrypt'"))
raise ValueError("keyword 'algorithm' must be either 'encrypt' "
"or 'decrypt'")

def sub_bytes(self, state, algorithm='encrypt'):
r"""
Expand Down Expand Up @@ -2010,8 +2010,8 @@ def _mix_columns_pc(self, row, col, algorithm='encrypt'):
elif algorithm == 'decrypt':
coeffs = self._mixcols_D
else:
raise ValueError(("keyword 'algorithm' must be either 'encrypt' "
"or 'decrypt'"))
raise ValueError("keyword 'algorithm' must be either 'encrypt' "
"or 'decrypt'")
return sum([coeffs[row,k] * self.state_vrs[k,col] for k in range(4)])

def mix_columns(self, state, algorithm='encrypt'):
Expand Down Expand Up @@ -2109,8 +2109,8 @@ def _shift_rows_pc(self, row, col, algorithm='encrypt'):
elif algorithm == 'decrypt':
offs = self._shiftrows_offsets_D
else:
raise ValueError(("keyword 'algorithm' must be either 'encrypt' "
"or 'decrypt'"))
raise ValueError("keyword 'algorithm' must be either 'encrypt' "
"or 'decrypt'")
return self.state_vrs[row, (col + offs[4 - self._Nb][row]) % 4]

def shift_rows(self, state, algorithm='encrypt'):
Expand Down
4 changes: 2 additions & 2 deletions src/sage/data_structures/stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@
lazy_import('sage.combinat.sf.sfa', ['_variables_recursive', '_raise_variables'])


class Stream():
class Stream:
"""
Abstract base class for all streams.
Expand Down Expand Up @@ -2410,7 +2410,7 @@ def stretched_power_restrict_degree(self, i, m, d):
_raise_variables(c, i, self._degree_one)
for mon, c in power_d}
else:
terms = {tuple((mu.stretch(i) for mu in mon)):
terms = {tuple(mu.stretch(i) for mu in mon):
_raise_variables(c, i, self._degree_one)
for mon, c in power_d}
return self._basis(self._p.element_class(self._p, terms))
Expand Down
6 changes: 3 additions & 3 deletions src/sage/databases/cremona.py
Original file line number Diff line number Diff line change
Expand Up @@ -1122,10 +1122,10 @@ def iter_optimal(self, conductors):
if N == 990:
for c in self.__connection__.cursor().execute('SELECT class '
+ 'FROM t_class WHERE conductor=990'):
if c[0][-1] == u'h':
yield self.elliptic_curve(c[0]+u'3')
if c[0][-1] == 'h':
yield self.elliptic_curve(c[0]+'3')
else:
yield self.elliptic_curve(c[0]+u'1')
yield self.elliptic_curve(c[0]+'1')
continue
for c in self.__connection__.cursor().execute('SELECT curve '
+ 'FROM t_curve,t_class USING(class) WHERE curve=class||1 '
Expand Down
2 changes: 1 addition & 1 deletion src/sage/databases/findstat.py
Original file line number Diff line number Diff line change
Expand Up @@ -4352,7 +4352,7 @@ def first_terms(self, function, level=None):
g = (x for x in self._sageconstructor_overridden
if self.element_level(x) == level)

return lazy_list(((x, function(x)) for x in g))
return lazy_list((x, function(x)) for x in g)

def id(self):
r"""
Expand Down
6 changes: 3 additions & 3 deletions src/sage/databases/sql_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ def construct_skeleton(database):
exe1 = cur.execute("PRAGMA table_info(%s)" % table[0])
for col in exe1.fetchall():
if not col[2]:
typ = u'NOTYPE'
typ = 'NOTYPE'
else:
typ = col[2]
skeleton[table[0]][col[1]] = {'sql':typ,
Expand Down Expand Up @@ -482,7 +482,7 @@ def __init__(self, database, *args, **kwds):
else:
self.__query_string__ = kwds['query_string']
if 'param_tuple' in kwds:
self.__param_tuple__ = tuple((str(x) for x in kwds['param_tuple']))
self.__param_tuple__ = tuple(str(x) for x in kwds['param_tuple'])
else:
self.__param_tuple__ = tuple()
return
Expand Down Expand Up @@ -2164,7 +2164,7 @@ def add_rows(self, table_name, rows, entry_order=None):
if self.__read_only__:
raise RuntimeError('Cannot add rows to read only database.')
quest = '(' + ', '.join('?' for i in rows[0]) + ')'
strows = [tuple((str(entry) for entry in row)) for row in rows]
strows = [tuple(str(entry) for entry in row) for row in rows]

if entry_order is not None:
self.__connection__.executemany('INSERT INTO ' + table_name
Expand Down
2 changes: 1 addition & 1 deletion src/sage/doctest/control.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ def skipfile(filename, tested_optional_tags=False, *,
return False


class Logger():
class Logger:
r"""
File-like object which implements writing to multiple files at
once.
Expand Down
2 changes: 1 addition & 1 deletion src/sage/doctest/external.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ def external_software() -> list[str]:
external_software = external_software()


class AvailableSoftware():
class AvailableSoftware:
"""
This class keeps the set of available software whose availability is detected lazily
from the list of external software.
Expand Down
4 changes: 2 additions & 2 deletions src/sage/doctest/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def sorted_pairs(iterable, pairs=False):
return repr(val)


class AttributeAccessTracerHelper():
class AttributeAccessTracerHelper:

def __init__(self, delegate, prefix=" ", reads=True):
r"""
Expand Down Expand Up @@ -223,7 +223,7 @@ def set(self, name, val):
setattr(self.delegate, name, val)


class AttributeAccessTracerProxy():
class AttributeAccessTracerProxy:

def __init__(self, delegate, **kwds):
r"""
Expand Down
2 changes: 1 addition & 1 deletion src/sage/doctest/forker.py
Original file line number Diff line number Diff line change
Expand Up @@ -2467,7 +2467,7 @@ def kill(self):
return True


class DocTestTask():
class DocTestTask:
"""
This class encapsulates the tests from a single source.
Expand Down
2 changes: 1 addition & 1 deletion src/sage/doctest/parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -652,7 +652,7 @@ def reduce_hex(fingerprints):
return "%032x" % res


class OriginalSource():
class OriginalSource:
r"""
Context swapping out the pre-parsed source with the original for
better reporting.
Expand Down
2 changes: 1 addition & 1 deletion src/sage/doctest/sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def get_basename(path):
return basename


class DocTestSource():
class DocTestSource:
"""
This class provides a common base class for different sources of doctests.
Expand Down
2 changes: 1 addition & 1 deletion src/sage/dynamics/arithmetic_dynamics/berkovich_ds.py
Original file line number Diff line number Diff line change
Expand Up @@ -869,7 +869,7 @@ def __call__(self, x, type_3_pole_check=True):
else:
new_poly.append(ring_of_integers(i).mod(ideal))
new_poly = R(new_poly)
fraction.append((new_poly))
fraction.append(new_poly)
gcd = fraction[0].gcd(fraction[1])
num = fraction[0].quo_rem(gcd)[0]
dem = fraction[1].quo_rem(gcd)[0]
Expand Down
18 changes: 9 additions & 9 deletions src/sage/dynamics/cellular_automata/glca.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,24 +363,24 @@ def _unicode_art_(self, number=None):
number = len(self._states)

space = len(self._states[:number]) * 2 - 1
ret = UnicodeArt([u' '*space + u'◾'])
ret = UnicodeArt([' '*space + '◾'])
space += 1
for i,state in enumerate(self._states[:number]):
temp = u' '*(space-2)
last = u' '
temp = ' '*(space-2)
last = ' '
for x in state:
if x & 0x4:
if last == u'╱':
temp += u'╳'
if last == '╱':
temp += '╳'
else:
temp += u'╲'
temp += '╲'
else:
temp += last
temp += u'│' if x & 0x2 else ' '
last = u'╱' if x & 0x1 else ' '
temp += '│' if x & 0x2 else ' '
last = '╱' if x & 0x1 else ' '
ret *= UnicodeArt([temp + last])
space -= 1
ret *= UnicodeArt([u' '*space + u' '.join(u'◾' for dummy in range(2*i+1))])
ret *= UnicodeArt([' '*space + ' '.join('◾' for dummy in range(2*i+1))])
space -= 1
return ret

Expand Down
1 change: 1 addition & 0 deletions src/sage/dynamics/complex_dynamics/mandel_julia.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,7 @@ def external_ray(theta, **kwds):
pixel[int(k[0]), int(k[1])] = tuple(ray_color)
return M


def kneading_sequence(theta):
r"""
Determines the kneading sequence for an angle theta in RR/ZZ which
Expand Down
2 changes: 1 addition & 1 deletion src/sage/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ def get_cblas_pc_module_name() -> str:
"""
import pkgconfig
cblas_pc_modules = CBLAS_PC_MODULES.split(':')
return next((blas_lib for blas_lib in cblas_pc_modules if pkgconfig.exists(blas_lib)))
return next(blas_lib for blas_lib in cblas_pc_modules if pkgconfig.exists(blas_lib))


default_required_modules = ('fflas-ffpack', 'givaro', 'gsl', 'linbox', 'Singular',
Expand Down
2 changes: 1 addition & 1 deletion src/sage/features/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ def __str__(self):
return "\n".join(lines)


class FeatureTestResult():
class FeatureTestResult:
r"""
The result of a :meth:`Feature.is_present` call.
Expand Down
Loading

0 comments on commit 3f58180

Please sign in to comment.