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

fixing some suggestions by ruff #38740

Merged
merged 3 commits into from
Oct 26, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@
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]])

Check warning on line 3062 in src/sage/categories/pushout.py

View check run for this annotation

Codecov / codecov/patch

src/sage/categories/pushout.py#L3062

Added line #L3062 was not covered by tests
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 @@
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' "

Check warning on line 616 in src/sage/crypto/mq/rijndael_gf.py

View check run for this annotation

Codecov / codecov/patch

src/sage/crypto/mq/rijndael_gf.py#L616

Added line #L616 was not covered by tests
"or 'decrypt'")

def __repr__(self):
r"""
Expand Down Expand Up @@ -981,8 +981,8 @@
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 "

Check warning on line 984 in src/sage/crypto/mq/rijndael_gf.py

View check run for this annotation

Codecov / codecov/patch

src/sage/crypto/mq/rijndael_gf.py#L984

Added line #L984 was not covered by tests
"'binary'")

state = self.add_round_key(state, roundKeys[0])
for r in range(self._Nr-1):
Expand Down Expand Up @@ -1057,8 +1057,8 @@
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 "

Check warning on line 1060 in src/sage/crypto/mq/rijndael_gf.py

View check run for this annotation

Codecov / codecov/patch

src/sage/crypto/mq/rijndael_gf.py#L1060

Added line #L1060 was not covered by tests
"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 @@
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 "

Check warning on line 1075 in src/sage/crypto/mq/rijndael_gf.py

View check run for this annotation

Codecov / codecov/patch

src/sage/crypto/mq/rijndael_gf.py#L1075

Added line #L1075 was not covered by tests
"'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 @@
else:
return result ** 254
else:
raise ValueError(("keyword 'algorithm' must be either 'encrypt' "
"or 'decrypt'"))
raise ValueError("keyword 'algorithm' must be either 'encrypt' "

Check warning on line 1877 in src/sage/crypto/mq/rijndael_gf.py

View check run for this annotation

Codecov / codecov/patch

src/sage/crypto/mq/rijndael_gf.py#L1877

Added line #L1877 was not covered by tests
"or 'decrypt'")

def _srd(self, el, algorithm='encrypt'):
r"""
Expand Down Expand Up @@ -1910,8 +1910,8 @@
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' "

Check warning on line 1913 in src/sage/crypto/mq/rijndael_gf.py

View check run for this annotation

Codecov / codecov/patch

src/sage/crypto/mq/rijndael_gf.py#L1913

Added line #L1913 was not covered by tests
"or 'decrypt'")

def sub_bytes(self, state, algorithm='encrypt'):
r"""
Expand Down Expand Up @@ -2010,8 +2010,8 @@
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' "

Check warning on line 2013 in src/sage/crypto/mq/rijndael_gf.py

View check run for this annotation

Codecov / codecov/patch

src/sage/crypto/mq/rijndael_gf.py#L2013

Added line #L2013 was not covered by tests
"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 @@
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' "

Check warning on line 2112 in src/sage/crypto/mq/rijndael_gf.py

View check run for this annotation

Codecov / codecov/patch

src/sage/crypto/mq/rijndael_gf.py#L2112

Added line #L2112 was not covered by tests
"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 @@
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)

Check warning on line 4355 in src/sage/databases/findstat.py

View check run for this annotation

Codecov / codecov/patch

src/sage/databases/findstat.py#L4355

Added line #L4355 was not covered by tests

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 @@
exe1 = cur.execute("PRAGMA table_info(%s)" % table[0])
for col in exe1.fetchall():
if not col[2]:
typ = u'NOTYPE'
typ = 'NOTYPE'

Check warning on line 257 in src/sage/databases/sql_db.py

View check run for this annotation

Codecov / codecov/patch

src/sage/databases/sql_db.py#L257

Added line #L257 was not covered by tests
else:
typ = col[2]
skeleton[table[0]][col[1]] = {'sql':typ,
Expand Down Expand Up @@ -482,7 +482,7 @@
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 @@
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
Loading