Skip to content

Commit

Permalink
gh-38698: some fixes for ruff UP warnings
Browse files Browse the repository at this point in the history
    
of various kinds, including typing annotations

### 📝 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: #38698
Reported by: Frédéric Chapoton
Reviewer(s):
  • Loading branch information
Release Manager committed Sep 27, 2024
2 parents 7721e53 + da94f62 commit 58ffd78
Show file tree
Hide file tree
Showing 37 changed files with 50 additions and 48 deletions.
2 changes: 1 addition & 1 deletion src/sage/combinat/combinat.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@
# https://www.gnu.org/licenses/
# ****************************************************************************
from __future__ import annotations
from typing import Iterator
from collections.abc import Iterator

from sage.arith.misc import bernoulli, factorial
from sage.rings.integer_ring import ZZ
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -538,7 +538,7 @@ def construction_q_x(k, q, x, check=True, explain_construction=False):
# Add rows, extended with p1 and p2
p1 = q**2
p2 = p1 + 1
TD.extend(([ii*q + i for ii in range(q)] + [p1] for i in range(1, q)))
TD.extend([ii*q + i for ii in range(q)] + [p1] for i in range(1, q))
TD.append([ii*q for ii in range(q)] + [p1, p2])

# Add Columns. We do not add some columns which would have size 1 after we
Expand Down
2 changes: 1 addition & 1 deletion src/sage/combinat/dyck_word.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@
# https://www.gnu.org/licenses/
# ****************************************************************************
from __future__ import annotations
from typing import Iterator
from collections.abc import Iterator

from .combinat import CombinatorialElement, catalan_number
from sage.combinat.combinatorial_map import combinatorial_map
Expand Down
2 changes: 1 addition & 1 deletion src/sage/combinat/parking_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
# https://www.gnu.org/licenses/
# ****************************************************************************
from __future__ import annotations
from typing import Iterator
from collections.abc import Iterator

from sage.rings.integer import Integer
from sage.rings.rational_field import QQ
Expand Down
3 changes: 2 additions & 1 deletion src/sage/combinat/plane_partition.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
# ****************************************************************************

from __future__ import annotations
from typing import NewType, Iterator
from typing import NewType
from collections.abc import Iterator

from sage.structure.richcmp import richcmp, richcmp_method
from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
Expand Down
2 changes: 1 addition & 1 deletion src/sage/combinat/subword.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
# https://www.gnu.org/licenses/
# ****************************************************************************
from __future__ import annotations
from typing import Iterator
from collections.abc import Iterator
import itertools

from sage.structure.parent import Parent
Expand Down
10 changes: 5 additions & 5 deletions src/sage/databases/cremona.py
Original file line number Diff line number Diff line change
Expand Up @@ -567,8 +567,8 @@ def cremona_to_lmfdb(cremona_label, CDB=None):
if CDB is None:
CDB = CremonaDatabase()
classes = CDB.isogeny_classes(N)
ft = int(53)
tff = int(255) # This should be enough to distinguish between curves (using heuristics from Sato-Tate for example)
ft = 53
tff = 255 # This should be enough to distinguish between curves (using heuristics from Sato-Tate for example)
isos = []
for i, iso in enumerate(classes):
alist = iso[0][0]
Expand Down Expand Up @@ -617,8 +617,8 @@ def lmfdb_to_cremona(lmfdb_label, CDB=None):
if CDB is None:
CDB = CremonaDatabase()
classes = CDB.isogeny_classes(N)
ft = int(53)
tff = int(255) # This should be enough to distinguish between curves (using heuristics from Sato-Tate for example)
ft = 53
tff = 255 # This should be enough to distinguish between curves (using heuristics from Sato-Tate for example)
isos = []
for i, iso in enumerate(classes):
alist = iso[0][0]
Expand Down Expand Up @@ -818,7 +818,7 @@ def curves(self, N):
ret[iso+str(num)] = [eval(c[1]),c[2],c[3]]
if N == 990:
del ret['h1']
ret['h3'] = [[1,-1,1,-1568,-4669],int(1),int(6)]
ret['h3'] = [[1,-1,1,-1568,-4669],1,6]
return ret

def coefficients_and_data(self, label):
Expand Down
2 changes: 1 addition & 1 deletion src/sage/databases/stein_watkins.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ def ecdb_num_curves(max_level=200000):
"""
i = 0
d = SteinWatkinsAllData(i)
v = [int(0) for _ in range(max_level + 1)]
v = [0 for _ in range(max_level + 1)]
while True:
try:
C = next(d)
Expand Down
2 changes: 1 addition & 1 deletion src/sage/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
# https://www.gnu.org/licenses/
# ****************************************************************************

from typing import List, Optional
from typing import Optional
import sage
import os
import socket
Expand Down
2 changes: 1 addition & 1 deletion src/sage/ext_data/nbconvert/postprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

file_name = sys.argv[1]

with open(file_name, 'r') as f:
with open(file_name) as f:
lines = f.readlines()

# states of the parser
Expand Down
2 changes: 1 addition & 1 deletion src/sage/game_theory/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ def format_gambit(self, gambit_game):
nice_stuff = []
for gambitstrategy in self.raw_string:
gambitstrategy = list(gambitstrategy)
profile = [tuple(gambitstrategy[:len(gambit_game.players[int(0)].strategies)])]
profile = [tuple(gambitstrategy[:len(gambit_game.players[0].strategies)])]
for player in list(gambit_game.players)[1:]:
previousplayerstrategylength = len(profile[-1])
profile.append(tuple(gambitstrategy[previousplayerstrategylength: previousplayerstrategylength + len(player.strategies)]))
Expand Down
2 changes: 1 addition & 1 deletion src/sage/graphs/bipartite_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -1753,7 +1753,7 @@ def load_afile(self, fname):
"""
# open the file
try:
fi = open(fname, "r")
fi = open(fname)
except OSError:
print("unable to open file <<" + fname + ">>")
return None
Expand Down
2 changes: 1 addition & 1 deletion src/sage/graphs/generic_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -22761,7 +22761,7 @@ def graphviz_to_file_named(self, filename, **options):
node_2 -- node_3 [label="foo"];
}
"""
with open(filename, 'wt') as file:
with open(filename, "w") as file:
file.write(self.graphviz_string(**options))

# Spectrum
Expand Down
4 changes: 2 additions & 2 deletions src/sage/graphs/graph_plot_js.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,13 +317,13 @@ def gen_html_code(G,
"edge_thickness": int(edge_thickness)})

from sage.env import SAGE_EXTCODE, SAGE_SHARE
with open(Path(SAGE_EXTCODE) / "graphs" / "graph_plot_js.html", 'r') as f:
with open(Path(SAGE_EXTCODE) / "graphs" / "graph_plot_js.html") as f:
js_code = f.read().replace("// GRAPH_DATA_HEREEEEEEEEEEE", string)

# Add d3.js script depending on whether d3js package is installed.
d3js_filepath = Path(SAGE_SHARE) / 'd3js' / 'd3.min.js'
if d3js_filepath.exists():
with open(d3js_filepath, 'r') as d3js_code_file:
with open(d3js_filepath) as d3js_code_file:
d3js_script = '<script>' + d3js_code_file.read() + '</script>'
else:
d3js_script = '<script src="http://d3js.org/d3.v3.min.js"></script>'
Expand Down
2 changes: 1 addition & 1 deletion src/sage/graphs/isgci.py
Original file line number Diff line number Diff line change
Expand Up @@ -832,7 +832,7 @@ def _parse_db(self):
inclusions = DB['Inclusions']['incl']

# Parses the list of ISGCI small graphs
smallgraph_file = open(os.path.join(data_dir, _SMALLGRAPHS_FILE), 'r')
smallgraph_file = open(os.path.join(data_dir, _SMALLGRAPHS_FILE))
smallgraphs = {}

for line in smallgraph_file.readlines():
Expand Down
2 changes: 1 addition & 1 deletion src/sage/interfaces/gap.py
Original file line number Diff line number Diff line change
Expand Up @@ -1314,7 +1314,7 @@ def help(self, s, pager=True):
sline = int(sline) - 1
if self.is_remote():
self._get_tmpfile()
with open(self._local_tmpfile(), "r",
with open(self._local_tmpfile(),
encoding=gap_encoding) as fobj:
help = fobj.read()
if pager:
Expand Down
2 changes: 1 addition & 1 deletion src/sage/interfaces/latte.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ def count(arg, ehrhart_polynomial=False, multivariate_generating_function=False,
if not ans:
# opening a file is slow (30e-6s), so we read the file
# numOfLatticePoints only in case of a IndexError above
with open(tempd.name + '/numOfLatticePoints', 'r') as f:
with open(tempd.name + '/numOfLatticePoints') as f:
ans = f.read()

if raw_output:
Expand Down
2 changes: 1 addition & 1 deletion src/sage/interfaces/read_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def read_data(f, t):
sage: l = read_data(indata, RealField(17)); l
[1.234, 5.678]
"""
with open(f, "r") as fp:
with open(f) as fp:
l = []
while True:
s = fp.readline().strip()
Expand Down
2 changes: 1 addition & 1 deletion src/sage/libs/gap/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def test_write_to_file():
fname = tmp_filename()
message = "Ceci n'est pas une groupe"
libgap.PrintTo(fname, message)
with open(fname, 'r') as f:
with open(fname) as f:
assert f.read() == message
SystemFile = libgap.function_factory('StringFile')
assert SystemFile(fname).sage() == message
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
# *****************************************************************************
from __future__ import annotations

from typing import Optional, Tuple
from typing import Optional

from sage.categories.manifolds import Manifolds
from sage.manifolds.differentiable.examples.euclidean import EuclideanSpace
Expand All @@ -43,7 +43,7 @@ def __init__(
symplectic_latex_name: Optional[str] = None,
start_index: int = 1,
base_manifold: Optional[StandardSymplecticSpace] = None,
names: Optional[Tuple[str]] = None,
names: Optional[tuple[str]] = None,
):
r"""
INPUT:
Expand Down
4 changes: 2 additions & 2 deletions src/sage/manifolds/differentiable/tensorfield.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
# *****************************************************************************
from __future__ import annotations

from typing import TYPE_CHECKING, Optional, Tuple, TypeVar, Union
from typing import TYPE_CHECKING, Optional, TypeVar, Union

from sage.rings.integer import Integer
from sage.rings.integer_ring import ZZ
Expand All @@ -72,7 +72,7 @@
from sage.tensor.modules.comp import Components


TensorType = Tuple[int, int]
TensorType = tuple[int, int]
T = TypeVar("T", bound='TensorField')


Expand Down
6 changes: 3 additions & 3 deletions src/sage/misc/package.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
# (at your option) any later version.
# https://www.gnu.org/licenses/
# ****************************************************************************
from typing import Dict, List, NamedTuple, Optional, Union
from typing import NamedTuple, Optional, Union

import sage.env

Expand Down Expand Up @@ -230,8 +230,8 @@ def is_installed(self) -> bool:
return self.installed_version is not None


def list_packages(*pkg_types: str, pkg_sources: List[str] = ['normal', 'pip', 'script'],
local: bool = False, ignore_URLError: bool = False, exclude_pip: bool = False) -> Dict[str, PackageInfo]:
def list_packages(*pkg_types: str, pkg_sources: list[str] = ['normal', 'pip', 'script'],
local: bool = False, ignore_URLError: bool = False, exclude_pip: bool = False) -> dict[str, PackageInfo]:
r"""
Return a dictionary of information about each package.
Expand Down
2 changes: 1 addition & 1 deletion src/sage/modular/hecke/algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
#
# https://www.gnu.org/licenses/
# ****************************************************************************
from typing import Iterator
from collections.abc import Iterator

from sage.rings.infinity import infinity
from sage.categories.algebras import Algebras
Expand Down
2 changes: 1 addition & 1 deletion src/sage/modular/multiple_zeta.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@
# ****************************************************************************
from __future__ import annotations
import numbers
from typing import Iterator
from collections.abc import Iterator
from itertools import product

from sage.misc.fast_methods import Singleton
Expand Down
2 changes: 1 addition & 1 deletion src/sage/modular/multiple_zeta_F_algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
# https://www.gnu.org/licenses/
# ****************************************************************************
from __future__ import annotations
from typing import Iterator
from collections.abc import Iterator

from sage.arith.misc import bernoulli
from sage.categories.rings import Rings
Expand Down
2 changes: 1 addition & 1 deletion src/sage/modules/with_basis/representation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1489,7 +1489,7 @@ def __classcall_private__(cls, reps, **options):
reps = sum((module._sets if isinstance(module, Representation_Tensor) else (module,) for module in reps), ())
if all('FiniteDimensional' in M.category().axioms() for M in reps):
options['category'] = options['category'].FiniteDimensional()
return super(Representation_Tensor, cls).__classcall__(cls, reps, **options)
return super().__classcall__(cls, reps, **options)

def __init__(self, reps, **options):
r"""
Expand Down
2 changes: 1 addition & 1 deletion src/sage/plot/arc.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def get_minmax_data(self):
if angle < 0:
angle += twopi

epsilon = float(0.0000001)
epsilon = 0.0000001

cos_angle = cos(angle)
sin_angle = sin(angle)
Expand Down
2 changes: 1 addition & 1 deletion src/sage/repl/ipython_extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,7 @@ def run_init(self):
Run Sage's initial startup file.
"""
try:
with open(SAGE_STARTUP_FILE, 'r') as f:
with open(SAGE_STARTUP_FILE) as f:
self.shell.run_cell(f.read(), store_history=False)
except OSError:
pass
Expand Down
2 changes: 1 addition & 1 deletion src/sage/rings/number_field/totallyreal_phc.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def __lagrange_bounds_phc(n, m, a, tmpfile=None):

os.remove(tmpfile + '.phc')
os.popen('phc -b ' + tmpfile + ' ' + tmpfile + '.phc')
f = open(tmpfile + '.phc', 'r')
f = open(tmpfile + '.phc')
f_str = f.read()
pos = f_str.find('= real ')
crits = []
Expand Down
2 changes: 1 addition & 1 deletion src/sage/rings/polynomial/multi_polynomial_element.py
Original file line number Diff line number Diff line change
Expand Up @@ -1603,7 +1603,7 @@ def univariate_polynomial(self, R=None):
return R(0)

#construct list
lookup = [int(0),] * len(next(iter(monomial_coefficients)))
lookup = [0,] * len(next(iter(monomial_coefficients)))
coefficients = []
for degree in range(max(m[var_idx]
for m in monomial_coefficients.keys()) + 1):
Expand Down
4 changes: 2 additions & 2 deletions src/sage/sat/solvers/dimacs.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ def write(self, filename=None):
tail.close()

head = open(headname,"a")
tail = open(self._tail.name,"r")
tail = open(self._tail.name)
head.write(tail.read())
tail.close()
head.close()
Expand Down Expand Up @@ -301,7 +301,7 @@ def clauses(self, filename=None):
else:
tail = self._tail
tail.close()
tail = open(self._tail.name,"r")
tail = open(self._tail.name)

clauses = []
for line in tail.readlines():
Expand Down
2 changes: 1 addition & 1 deletion src/sage/sets/image_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
# https://www.gnu.org/licenses/
# ****************************************************************************

from typing import Iterator
from collections.abc import Iterator

from sage.categories.map import Map
from sage.categories.poor_man_map import PoorManMap
Expand Down
3 changes: 2 additions & 1 deletion src/sage/tensor/modules/finite_rank_free_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,7 +535,8 @@ class :class:`~sage.modules.free_module.FreeModule_generic`
# ******************************************************************************
from __future__ import annotations

from typing import Generator, Optional
from typing import Optional
from collections.abc import Generator

from sage.categories.fields import Fields
from sage.categories.homset import Hom
Expand Down
4 changes: 2 additions & 2 deletions src/sage/tensor/modules/free_module_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ class being:
# *****************************************************************************
from __future__ import annotations

from typing import TYPE_CHECKING, Dict, Optional, Union
from typing import TYPE_CHECKING, Optional, Union

from sage.parallel.decorate import parallel
from sage.parallel.parallelism import Parallelism
Expand Down Expand Up @@ -310,7 +310,7 @@ def __init__(
self._latex_name = self._name
else:
self._latex_name = latex_name
self._components: Dict[FreeModuleBasis, Components] = {} # dict. of the sets of components on various
self._components: dict[FreeModuleBasis, Components] = {} # dict. of the sets of components on various
# bases, with the bases as keys (initially empty)

# Treatment of symmetry declarations:
Expand Down
2 changes: 1 addition & 1 deletion src/sage/tests/memcheck/verify_no_leak.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Tuple, Sequence, List, Callable, Any
from typing import Callable, Any
import valgrind


Expand Down
2 changes: 1 addition & 1 deletion src/sage/topology/simplicial_set_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -657,7 +657,7 @@ def simplicial_data_from_kenzo_output(filename) -> dict:
"""
from pyparsing import OneOrMore, nestedExpr

with open(filename, 'r') as f:
with open(filename) as f:
data = f.read()
dim = 0
start = 0
Expand Down
Loading

0 comments on commit 58ffd78

Please sign in to comment.