Skip to content

Commit 31d8d5b

Browse files
author
Release Manager
committed
gh-36440: trying ruff on some posets files This is changing two files in the posets folder. - use a smaller doctest in one place - replace one annoying use of `deepcopy` by the method `copy` of `DiGraph` - apply `ruff check --fix --select UP src/sage/combinat/posets` to make a few automatic modifications, about strings mostly, and about the syntax of `super` - avoid one symbolic number in one doctest ### 📝 Checklist - [x] The title is concise, informative, and self-explanatory. - [x] The description explains in detail what this PR is about. URL: #36440 Reported by: Frédéric Chapoton Reviewer(s): David Coudert
2 parents 0cdf0b3 + 43b7629 commit 31d8d5b

File tree

2 files changed

+18
-22
lines changed

2 files changed

+18
-22
lines changed

src/sage/combinat/posets/incidence_algebras.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def __init__(self, R, P, prefix='I'):
5858
5959
TESTS::
6060
61-
sage: P = posets.BooleanLattice(4)
61+
sage: P = posets.BooleanLattice(3)
6262
sage: I = P.incidence_algebra(QQ)
6363
sage: TestSuite(I).run() # long time
6464
"""
@@ -93,8 +93,7 @@ def _repr_(self):
9393
Incidence algebra of Finite lattice containing 16 elements
9494
over Rational Field
9595
"""
96-
return "Incidence algebra of {} over {}".format(self._poset,
97-
self.base_ring())
96+
return f"Incidence algebra of {self._poset} over {self.base_ring()}"
9897

9998
def _coerce_map_from_(self, R):
10099
"""

src/sage/combinat/posets/posets.py

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
# sage.doctest: needs sage.graphs sage.modules
32
r"""
43
Finite posets
@@ -287,9 +286,8 @@
287286
# ****************************************************************************
288287
from __future__ import annotations
289288
from collections import defaultdict
290-
from copy import copy, deepcopy
289+
from copy import copy
291290
from itertools import product
292-
from typing import List
293291

294292
from sage.misc.cachefunc import cached_method
295293
from sage.misc.lazy_attribute import lazy_attribute
@@ -706,7 +704,7 @@ def Poset(data=None, element_labels=None, cover_relations=False, linear_extensio
706704
if data is None: # type 0
707705
D = DiGraph()
708706
elif isinstance(data, DiGraph): # type 4
709-
D = deepcopy(data)
707+
D = data.copy(immutable=True)
710708
elif isinstance(data, dict): # type 3: dictionary of upper covers
711709
D = DiGraph(data, format="dict_of_lists")
712710
elif isinstance(data, (list, tuple)): # types 1, 2, 3 (list/tuple)
@@ -1319,7 +1317,7 @@ def __call__(self, element):
13191317
"""
13201318
if self._is_facade and element in self._element_to_vertex_dict:
13211319
return element
1322-
return super(FinitePoset, self).__call__(element)
1320+
return super().__call__(element)
13231321

13241322
def hasse_diagram(self):
13251323
r"""
@@ -1403,7 +1401,7 @@ def _repr_(self):
14031401
sage: M._repr_()
14041402
'Finite meet-semilattice containing 3 elements'
14051403
"""
1406-
s = "%s containing %s elements" % (self._desc, self._hasse_diagram.order())
1404+
s = f"{self._desc} containing {self._hasse_diagram.order()} elements"
14071405
if self._with_linear_extension:
14081406
s += " with distinguished linear extension"
14091407
return s
@@ -1444,13 +1442,13 @@ def _rich_repr_(self, display_manager, **kwds):
14441442
return output
14451443
# create text for non-graphical output
14461444
if can_plot:
1447-
text = '{0} (use the .plot() method to plot)'.format(repr(self))
1445+
text = f'{repr(self)} (use the .plot() method to plot)'
14481446
else:
14491447
text = repr(self)
14501448
# latex() produces huge tikz environment, override
14511449
tp = display_manager.types
14521450
if (prefs.text == 'latex' and tp.OutputLatex in display_manager.supported_output()):
1453-
return tp.OutputLatex(r'\text{{{0}}}'.format(text))
1451+
return tp.OutputLatex(fr'\text{{{text}}}')
14541452
return tp.OutputPlainText(text)
14551453

14561454
def __iter__(self):
@@ -2669,7 +2667,7 @@ def relations_number(self):
26692667
# Maybe this should also be deprecated.
26702668
intervals_number = relations_number
26712669

2672-
def linear_intervals_count(self) -> List[int]:
2670+
def linear_intervals_count(self) -> list[int]:
26732671
"""
26742672
Return the enumeration of linear intervals w.r.t. their cardinality.
26752673
@@ -2799,10 +2797,10 @@ def is_incomparable_chain_free(self, m, n=None) -> bool:
27992797
sage: Q = Poset({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})
28002798
sage: Q.is_incomparable_chain_free(2, 20/10)
28012799
True
2802-
sage: Q.is_incomparable_chain_free(2, pi) # needs sage.symbolic
2800+
sage: Q.is_incomparable_chain_free(2, 1.5)
28032801
Traceback (most recent call last):
28042802
...
2805-
TypeError: 2 and pi must be integers
2803+
TypeError: 2 and 1.5... must be integers
28062804
sage: Q.is_incomparable_chain_free(2, -1)
28072805
Traceback (most recent call last):
28082806
...
@@ -2850,9 +2848,9 @@ def is_incomparable_chain_free(self, m, n=None) -> bool:
28502848
try:
28512849
m, n = Integer(m), Integer(n)
28522850
except TypeError:
2853-
raise TypeError("%s and %s must be integers" % (m, n))
2851+
raise TypeError(f"{m} and {n} must be integers")
28542852
if m < 1 or n < 1:
2855-
raise ValueError("%s and %s must be positive integers" % (m, n))
2853+
raise ValueError(f"{m} and {n} must be positive integers")
28562854
twochains = digraphs.TransitiveTournament(m) + digraphs.TransitiveTournament(n)
28572855
if closure.subgraph_search(twochains, induced=True) is not None:
28582856
return False
@@ -6348,7 +6346,7 @@ def graphviz_string(self, graph_string="graph", edge_string="--"):
63486346
s += '"%s";' % v
63496347
s += '\n'
63506348
for u, v in self.cover_relations_iterator():
6351-
s += '"%s"%s"%s";' % (v, edge_string, u)
6349+
s += f'"{v}"{edge_string}"{u}";'
63526350
s += "\n}"
63536351
return s
63546352

@@ -8152,9 +8150,9 @@ def is_eulerian(self, k=None, certificate=False):
81528150
try:
81538151
k = Integer(k)
81548152
except TypeError:
8155-
raise TypeError("parameter 'k' must be an integer, not {0}".format(k))
8153+
raise TypeError(f"parameter 'k' must be an integer, not {k}")
81568154
if k <= 0:
8157-
raise ValueError("parameter 'k' must be positive, not {0}".format(k))
8155+
raise ValueError(f"parameter 'k' must be positive, not {k}")
81588156

81598157
if not self.is_bounded():
81608158
raise ValueError("the poset is not bounded")
@@ -8880,7 +8878,7 @@ def _macaulay2_init_(self, macaulay2=None):
88808878
H = self._hasse_diagram
88818879
txt = 'needsPackage "Posets";'
88828880
txt += "poset({%s},{" % ','.join(str(x) for x in H)
8883-
txt += ",".join("{%s,%s}" % (str(x), str(y))
8881+
txt += ",".join(f"{{{str(x)},{str(y)}}}"
88848882
for x, y in H.cover_relations_iterator())
88858883
return txt + "})"
88868884

@@ -8993,8 +8991,7 @@ def cardinality(self, from_iterator=False):
89938991
68275077901156, 4483130665195087]
89948992
if not from_iterator and self._n < len(known_values):
89958993
return Integer(known_values[self._n])
8996-
else:
8997-
return super(FinitePosets_n, self).cardinality()
8994+
return super().cardinality()
89988995

89998996

90008997
# For backward compatibility of pickles of the former Posets()

0 commit comments

Comments
 (0)