Skip to content

Commit

Permalink
sagemathgh-37232: Still less use of isinstance of old-parents
Browse files Browse the repository at this point in the history
    
this is removing many calls to isinstance of old-style parent-like
classes

one should use instead the corresponding containment in categories

the case of `Finitefield` is kept for another time

### 📝 Checklist

- [x] The title is concise, informative, and self-explanatory.
- [x] The description explains in detail what this PR is about.
    
URL: sagemath#37232
Reported by: Frédéric Chapoton
Reviewer(s): Martin Rubey, Matthias Köppe
  • Loading branch information
Release Manager committed Feb 11, 2024
2 parents 3d38254 + 5d6033d commit cd61411
Show file tree
Hide file tree
Showing 14 changed files with 50 additions and 61 deletions.
7 changes: 2 additions & 5 deletions src/sage/algebras/algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
# http://www.gnu.org/licenses/
#*****************************************************************************

from sage.rings.ring import Algebra
from sage.categories.algebras import Algebras


def is_Algebra(x):
r"""
Return True if x is an Algebra.
Expand All @@ -37,7 +37,4 @@ def is_Algebra(x):
"""
from sage.misc.superseded import deprecation
deprecation(35253, "the function is_Algebra is deprecated; use '... in Algebras(base_ring)' instead")
try:
return isinstance(x, Algebra) or x in Algebras(x.base_ring())
except Exception:
return False
return x in Algebras(x.base_ring())
12 changes: 6 additions & 6 deletions src/sage/algebras/all.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
"""
Algebras
"""

#*****************************************************************************
# ****************************************************************************
# Copyright (C) 2005 William Stein <wstein@gmail.com>
#
# Distributed under the terms of the GNU General Public License (GPL)
Expand All @@ -14,10 +13,13 @@
#
# The full text of the GPL is available at:
#
# http://www.gnu.org/licenses/
#*****************************************************************************
# https://www.gnu.org/licenses/
# ****************************************************************************
from sage.misc.lazy_import import lazy_import

# old-style class for associative algebras, use Parent instead
from sage.rings.ring import Algebra

import sage.algebras.catalog as algebras

from .quatalg.all import *
Expand All @@ -28,11 +30,9 @@
from .lie_conformal_algebras.all import *

# Algebra base classes
from .algebra import Algebra
from .free_algebra import FreeAlgebra
from .free_algebra_quotient import FreeAlgebraQuotient


from .finite_dimensional_algebras.all import FiniteDimensionalAlgebra

lazy_import('sage.algebras.group_algebra', 'GroupAlgebra')
Expand Down
5 changes: 1 addition & 4 deletions src/sage/categories/algebras.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,7 @@ def __contains__(self, x):
sage: QQ['x'] in Algebras(CDF) # needs sage.rings.complex_double
False
"""
if super().__contains__(x):
return True
from sage.rings.ring import Algebra
return isinstance(x, Algebra) and x.base_ring() == self.base_ring()
return super().__contains__(x)

# def extra_super_categories(self):
# """
Expand Down
8 changes: 4 additions & 4 deletions src/sage/matrix/matrix0.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ from sage.misc.misc_c cimport normalize_index

from sage.categories.fields import Fields
from sage.categories.integral_domains import IntegralDomains
from sage.categories.commutative_rings import CommutativeRings
from sage.categories.rings import Rings

from sage.rings.ring cimport CommutativeRing
from sage.rings.ring import is_Ring
import sage.rings.abc
from sage.rings.integer_ring import is_IntegerRing

Expand Down Expand Up @@ -1660,7 +1660,7 @@ cdef class Matrix(sage.structure.element.Matrix):
[---]
[2 4]
"""
if not is_Ring(ring):
if ring not in Rings():
raise TypeError("ring must be a ring")

if ring is self._base_ring:
Expand Down Expand Up @@ -5323,7 +5323,7 @@ cdef class Matrix(sage.structure.element.Matrix):
[ -x*y*x*y x*y*x + x*y^2 x*y*x - x*y^2]
"""
# derived classes over a commutative base *just* overload _lmul_ (!!)
if isinstance(self._base_ring, CommutativeRing):
if self._base_ring in CommutativeRings():
return self._lmul_(left)
cdef Py_ssize_t r,c
x = self._base_ring(left)
Expand Down
10 changes: 4 additions & 6 deletions src/sage/modular/abvar/homology.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,11 @@
# https://www.gnu.org/licenses/
# ****************************************************************************

from sage.categories.commutative_rings import CommutativeRings
from sage.modular.hecke.module import HeckeModule_free_module
from sage.rings.integer import Integer
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.ring import CommutativeRing
from sage.structure.richcmp import richcmp_method, richcmp, richcmp_not_equal

# TODO: we will probably also need homology that is *not* a Hecke module.
Expand All @@ -74,11 +74,9 @@ def hecke_polynomial(self, n, var='x'):
INPUT:
- ``n`` -- positive integer
- ``n`` - positive integer
- ``var`` - string (default: 'x') the variable name
- ``var`` -- string (default: 'x') the variable name
OUTPUT: a polynomial over ZZ in the given variable
Expand Down Expand Up @@ -117,7 +115,7 @@ def __init__(self, abvar, base):
sage: loads(dumps(H)) == H
True
"""
if not isinstance(base, CommutativeRing):
if base not in CommutativeRings():
raise TypeError("base ring must be a commutative ring")
HeckeModule_free_module.__init__(
self, base, abvar.level(), weight=2)
Expand Down
4 changes: 2 additions & 2 deletions src/sage/modular/hecke/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from sage.modules.module import Module
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.ring import CommutativeRing
from sage.categories.commutative_rings import CommutativeRings
from sage.structure.sequence import Sequence

from . import algebra
Expand Down Expand Up @@ -76,7 +76,7 @@ def __init__(self, base_ring, level, category=None):
sage: ModularForms(3, 3).category()
Category of Hecke modules over Rational Field
"""
if not isinstance(base_ring, CommutativeRing):
if base_ring not in CommutativeRings():
raise TypeError("base_ring must be commutative ring")

from sage.categories.hecke_modules import HeckeModules
Expand Down
6 changes: 3 additions & 3 deletions src/sage/modular/modform/constructor.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
import sage.modular.dirichlet as dirichlet
from sage.rings.integer import Integer
from sage.rings.rational_field import Q as QQ
from sage.rings.ring import CommutativeRing
from sage.categories.commutative_rings import CommutativeRings

from .ambient_eps import ModularFormsAmbient_eps
from .ambient_g0 import ModularFormsAmbient_g0_Q
Expand Down Expand Up @@ -122,11 +122,11 @@ def canonical_parameters(group, level, weight, base_ring):
except TypeError:
raise TypeError("group of unknown type.")
level = Integer(level)
if ( m != level ):
if m != level:
raise ValueError("group and level do not match.")
group = arithgroup.Gamma0(m)

if not isinstance(base_ring, CommutativeRing):
if base_ring not in CommutativeRings():
raise TypeError("base_ring (=%s) must be a commutative ring" % base_ring)

# it is *very* important to include the level as part of the data
Expand Down
7 changes: 4 additions & 3 deletions src/sage/modular/modsym/modsym.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,11 @@

import weakref

from sage.categories.commutative_rings import CommutativeRings
from sage.categories.fields import Fields
import sage.modular.arithgroup.all as arithgroup
import sage.modular.dirichlet as dirichlet
from sage.rings.integer import Integer
from sage.rings.ring import CommutativeRing
from sage.rings.rational_field import RationalField


Expand Down Expand Up @@ -153,10 +154,10 @@ def canonical_parameters(group, weight, sign, base_ring):
if base_ring is None:
base_ring = RationalField()

if not isinstance(base_ring, CommutativeRing):
elif base_ring not in CommutativeRings():
raise TypeError(f"base_ring (={base_ring}) must be a commutative ring")

if not base_ring.is_field():
elif base_ring not in Fields():
raise TypeError(f"(currently) base_ring (={base_ring}) must be a field")

return group, weight, sign, base_ring
Expand Down
4 changes: 2 additions & 2 deletions src/sage/modular/quatalg/brandt.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@
# ****************************************************************************

from sage.arith.misc import gcd, factor, prime_divisors, kronecker, next_prime
from sage.categories.commutative_rings import CommutativeRings
from sage.matrix.constructor import matrix
from sage.matrix.matrix_space import MatrixSpace
from sage.misc.cachefunc import cached_method
Expand All @@ -219,7 +220,6 @@
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.power_series_ring import PowerSeriesRing
from sage.rings.rational_field import QQ
from sage.rings.ring import CommutativeRing
from sage.structure.richcmp import richcmp, richcmp_method

lazy_import('sage.algebras.quatalg.quaternion_algebra', ['QuaternionAlgebra', 'basis_for_quaternion_lattice'])
Expand Down Expand Up @@ -300,7 +300,7 @@ def BrandtModule(N, M=1, weight=2, base_ring=QQ, use_cache=True):
raise ValueError("M must be coprime to N")
if weight < 2:
raise ValueError("weight must be at least 2")
if not isinstance(base_ring, CommutativeRing):
if base_ring not in CommutativeRings():
raise TypeError("base_ring must be a commutative ring")
key = (N, M, weight, base_ring)
if use_cache:
Expand Down
5 changes: 3 additions & 2 deletions src/sage/rings/commutative_algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
# http://www.gnu.org/licenses/
#*****************************************************************************

from sage.rings.ring import CommutativeAlgebra
from sage.categories.commutative_algebras import CommutativeAlgebras


def is_CommutativeAlgebra(x):
"""
Expand All @@ -35,4 +36,4 @@ def is_CommutativeAlgebra(x):
"""
from sage.misc.superseded import deprecation
deprecation(35253, "the function is_CommutativeAlgebra is deprecated; use '... in Algebras(base_ring).Commutative()' instead")
return isinstance(x, CommutativeAlgebra)
return x in CommutativeAlgebras(x.base_ring())
19 changes: 8 additions & 11 deletions src/sage/rings/polynomial/skew_polynomial_ring.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
from sage.structure.richcmp import op_EQ, op_NE
from sage.structure.category_object import normalize_names

from sage.rings.ring import Field
from sage.categories.fields import Fields
from sage.matrix.matrix_space import MatrixSpace

from sage.rings.morphism import RingHomomorphism
Expand Down Expand Up @@ -85,17 +85,14 @@ def _base_ring_to_fraction_field(S):
Ore Polynomial Ring in x over Fraction Field of Univariate Polynomial Ring in t over Integer Ring twisted by t |--> t + 1
"""
R = S.base_ring()
if isinstance(R, Field):
if R in Fields():
return S
else:
Q = R.fraction_field()
gens = R.gens()
sigmaS = S.twisting_morphism()
# try:
sigmaQ = Q.hom([Q(sigmaS(g)) for g in gens])
return Q[S.variable_name(), sigmaQ]
# except Exception, e:
# raise ValueError("unable to lift the twisting morphism to a twisting morphism over %s (error was: %s)" % (Q, e))

Q = R.fraction_field()
gens = R.gens()
sigmaS = S.twisting_morphism()
sigmaQ = Q.hom([Q(sigmaS(g)) for g in gens])
return Q[S.variable_name(), sigmaQ]


def _minimal_vanishing_polynomial(R, eval_pts):
Expand Down
8 changes: 3 additions & 5 deletions src/sage/schemes/hyperelliptic_curves/monsky_washnitzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
from sage.rings.laurent_series_ring import LaurentSeriesRing
from sage.rings.rational_field import QQ
from sage.rings.integer_ring import ZZ
from sage.rings.ring import IntegralDomain
from sage.categories.integral_domains import IntegralDomains
from sage.rings.infinity import Infinity
from sage.rings.laurent_series_ring import is_LaurentSeriesRing
from sage.rings.padics.factory import Qp as pAdicField
Expand Down Expand Up @@ -3837,13 +3837,11 @@ def helper_matrix(self):
pass

# The smallest y term of (1/j) d(x^i y^j) is constant for all j.
L = []
x, y = self.base_ring().gens()
n = self.degree()
for i in range(n):
L.append((y*x**i).diff().extract_pow_y(0))
L = [(y * x**i).diff().extract_pow_y(0) for i in range(n)]
A = matrix(L).transpose()
if not isinstance(A.base_ring(), IntegralDomain):
if A.base_ring() not in IntegralDomains():
# must be using integer_mod or something to approximate
self._helper_matrix = (~A.change_ring(QQ)).change_ring(A.base_ring())
else:
Expand Down
10 changes: 5 additions & 5 deletions src/sage/schemes/plane_conics/constructor.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@

from sage.matrix.constructor import Matrix
from sage.modules.free_module_element import vector
from sage.rings.ring import IntegralDomain
from sage.categories.integral_domains import IntegralDomains
from sage.rings.rational_field import is_RationalField
from sage.rings.finite_rings.finite_field_base import FiniteField
from sage.rings.fraction_field import is_FractionField
Expand Down Expand Up @@ -143,7 +143,7 @@ def Conic(base_field, F=None, names=None, unique=True):
sage: Conic([a([x,x^2]) for x in range(5)])
Projective Conic Curve over Finite Field of size 13 defined by x^2 - y*z
"""
if not (base_field is None or isinstance(base_field, IntegralDomain)):
if not (base_field is None or base_field in IntegralDomains()):
if names is None:
names = F
F = base_field
Expand Down Expand Up @@ -173,7 +173,7 @@ def Conic(base_field, F=None, names=None, unique=True):
if len(C) != 3:
raise TypeError("points in F (=%s) must be planar" % F)
P = C.universe()
if not isinstance(P, IntegralDomain):
if P not in IntegralDomains():
raise TypeError("coordinates of points in F (=%s) must "
"be in an integral domain" % F)
L.append(Sequence([C[0]**2, C[0] * C[1],
Expand Down Expand Up @@ -217,8 +217,8 @@ def Conic(base_field, F=None, names=None, unique=True):

if base_field is None:
base_field = F.base_ring()
if not isinstance(base_field, IntegralDomain):
raise ValueError("Base field (=%s) must be a field" % base_field)
if base_field not in IntegralDomains():
raise ValueError(f"Base field (={base_field}) must be a field")
base_field = base_field.fraction_field()
if names is None:
names = F.parent().variable_names()
Expand Down
6 changes: 3 additions & 3 deletions src/sage/structure/element.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -3335,20 +3335,20 @@ cdef class CommutativeRingElement(RingElement):
#This code is very general, it works for all integral domains that have the
#is_square(root = True) option

from sage.rings.ring import IntegralDomain
from sage.categories.integral_domains import IntegralDomains
P = self._parent
is_sqr, sq_rt = self.is_square(root=True)
if is_sqr:
if all:
if not isinstance(P, IntegralDomain):
if P not in IntegralDomains():
raise NotImplementedError('sqrt() with all=True is only implemented for integral domains, not for %s' % P)
if P.characteristic()==2 or sq_rt==0:
#0 has only one square root, and in characteristic 2 everything also has only 1 root
return [ sq_rt ]
return [ sq_rt, -sq_rt ]
return sq_rt
#from now on we know that self is not a square
if not isinstance(P, IntegralDomain):
if P not in IntegralDomains():
raise NotImplementedError('sqrt() of non squares is only implemented for integral domains, not for %s' % P)
if not extend:
#all square roots of a non-square should be an empty list
Expand Down

0 comments on commit cd61411

Please sign in to comment.