Skip to content

Commit

Permalink
Trac #33696: simplify some isinstance
Browse files Browse the repository at this point in the history
using the shorter (and more efficient ?) syntax

URL: https://trac.sagemath.org/33696
Reported by: chapoton
Ticket author(s): Frédéric Chapoton
Reviewer(s): Matthias Koeppe
  • Loading branch information
Release Manager committed May 22, 2022
2 parents 7a8aa66 + 1747c10 commit fd6379f
Show file tree
Hide file tree
Showing 33 changed files with 46 additions and 47 deletions.
2 changes: 1 addition & 1 deletion src/sage/categories/pushout.py
Expand Up @@ -1378,7 +1378,7 @@ def __mul__(self, other):
# even respecting the order. Note that, if the pushout is computed, only *one* variable
# will occur in the polynomial constructor. Hence, any order is fine, which is exactly
# what we need in order to have coercion maps for different orderings.
if isinstance(other, MultiPolynomialFunctor) or isinstance(other, PolynomialFunctor):
if isinstance(other, (MultiPolynomialFunctor, PolynomialFunctor)):
if isinstance(other, MultiPolynomialFunctor):
othervars = other.vars
else:
Expand Down
2 changes: 1 addition & 1 deletion src/sage/dynamics/arithmetic_dynamics/affine_ds.py
Expand Up @@ -718,7 +718,7 @@ def orbit(self, P, n):
((-t^16 + 3*t^13 - 3*t^10 + t^7 + t^5 + t^3 - 1)/(t^5 + t^3 - 1), -t^9 - t^7 + t^4)]
"""
Q = P
if isinstance(n, list) or isinstance(n, tuple):
if isinstance(n, (list, tuple)):
bounds = list(n)
else:
bounds = [0,n]
Expand Down
2 changes: 1 addition & 1 deletion src/sage/geometry/polyhedron/backend_normaliz.py
Expand Up @@ -1196,7 +1196,7 @@ def format_number(x):
return '({})'.format(x.polynomial('a'))

def format_field(key, value):
if isinstance(value, list) or isinstance(value, tuple):
if isinstance(value, (list, tuple)):
s = '{} {}\n'.format(key, len(value))
for e in value:
for x in e:
Expand Down
2 changes: 1 addition & 1 deletion src/sage/interfaces/maxima_lib.py
Expand Up @@ -1589,7 +1589,7 @@ def sr_to_max(expr):
"""
global sage_op_dict, max_op_dict
global sage_sym_dict, max_sym_dict
if isinstance(expr,list) or isinstance(expr,tuple):
if isinstance(expr, (list, tuple)):
return EclObject(([mlist],[sr_to_max(e) for e in expr]))
op = expr.operator()
if op:
Expand Down
2 changes: 1 addition & 1 deletion src/sage/libs/giac/giac.pyx
Expand Up @@ -978,7 +978,7 @@ cdef class Pygen(GiacMethods_base):
cdef gen result
if(self._type == 7) or (self._type == 12): #if self is a list or a string
if isinstance(i,int) or isinstance(i,Integer):
if isinstance(i, (int, Integer)):
n=len(self)
if(i<n)and(-i<=n):
if(i<0):
Expand Down
6 changes: 3 additions & 3 deletions src/sage/libs/mpmath/ext_main.pyx
Expand Up @@ -127,7 +127,7 @@ cdef int MPF_set_any(MPF *re, MPF *im, x, MPopts opts, bint str_tuple_ok) except
MPF_set(re, &(<mpc>x).re)
MPF_set(im, &(<mpc>x).im)
return 2
if isinstance(x, int) or isinstance(x, long) or isinstance(x, Integer):
if isinstance(x, (int, Integer)):
MPF_set_int(re, x)
return 1
if isinstance(x, float):
Expand Down Expand Up @@ -995,7 +995,7 @@ cdef class Context:
"""
cdef MPF v
cdef bint ismpf, ismpc
if isinstance(x, int) or isinstance(x, long) or isinstance(x, Integer):
if isinstance(x, (int, Integer)):
return int(x), 'Z'
if isinstance(x, tuple):
p, q = x
Expand Down Expand Up @@ -1072,7 +1072,7 @@ cdef class Context:
"""
cdef int typ
if isinstance(x, int) or isinstance(x, long) or isinstance(x, Integer):
if isinstance(x, (int, Integer)):
mpz_set_integer(tmp_opx_re.man, x)
if mpz_sgn(tmp_opx_re.man) == 0:
return global_context.ninf
Expand Down
2 changes: 1 addition & 1 deletion src/sage/libs/mpmath/utils.pyx
Expand Up @@ -334,7 +334,7 @@ def sage_to_mpmath(x, prec):
from sage.rings.complex_mpfr import ComplexField
x = ComplexField(prec)(x)
return x._mpmath_()
if isinstance(x, tuple) or isinstance(x, list):
if isinstance(x, (tuple, list)):
return type(x)([sage_to_mpmath(v, prec) for v in x])
if isinstance(x, dict):
return dict([(k, sage_to_mpmath(v, prec)) for (k, v) in x.items()])
Expand Down
2 changes: 1 addition & 1 deletion src/sage/libs/ntl/ntl_GF2.pyx
Expand Up @@ -56,7 +56,7 @@ cdef class ntl_GF2(object):
"""
if isinstance(v, ntl_GF2):
self.x = (<ntl_GF2>v).x
elif isinstance(v, int) or isinstance(v, long) or isinstance(v, Integer):
elif isinstance(v, (int, Integer)):
GF2_conv_long(self.x, int(v) % 2)
elif v is not None:
ccreadstr(self.x, str(v))
Expand Down
2 changes: 1 addition & 1 deletion src/sage/libs/ntl/ntl_ZZX.pyx
Expand Up @@ -131,7 +131,7 @@ cdef class ntl_ZZX(object):

if v is None:
return
elif isinstance(v, list) or isinstance(v, tuple):
elif isinstance(v, (list, tuple)):
for i from 0 <= i < len(v):
x = v[i]
if not isinstance(x, ntl_ZZ):
Expand Down
2 changes: 1 addition & 1 deletion src/sage/libs/ntl/ntl_ZZ_pE.pyx
Expand Up @@ -113,7 +113,7 @@ cdef class ntl_ZZ_pE(object):
if (<ntl_ZZ_pX>v).c is not self.c.pc:
raise ValueError("You cannot cast between rings with different moduli")
self.x = ZZ_pX_to_ZZ_pE((<ntl_ZZ_pX>v).x)
elif isinstance(v, list) or isinstance(v, tuple):
elif isinstance(v, (list, tuple)):
tmp_zzpx = <ntl_ZZ_pX>ntl_ZZ_pX(v, self.c.pc)
self.c.restore_c() # allocating tmp_zzpx can change the current modulus trac #25790
self.x = ZZ_pX_to_ZZ_pE(tmp_zzpx.x)
Expand Down
2 changes: 1 addition & 1 deletion src/sage/libs/ntl/ntl_ZZ_pEX.pyx
Expand Up @@ -87,7 +87,7 @@ cdef class ntl_ZZ_pEX(object):

if v is None:
return
elif isinstance(v, list) or isinstance(v, tuple):
elif isinstance(v, (list, tuple)):
for i from 0 <= i < len(v):
x = v[i]
if not isinstance(x, ntl_ZZ_pE):
Expand Down
5 changes: 2 additions & 3 deletions src/sage/libs/singular/function.pyx
Expand Up @@ -531,7 +531,7 @@ cdef class Converter(SageObject):
isinstance(a, NCPolynomialIdeal):
v = self.append_ideal(a)

elif isinstance(a, int) or isinstance(a, long):
elif isinstance(a, int):
v = self.append_int(a)

elif isinstance(a, str):
Expand Down Expand Up @@ -1427,8 +1427,7 @@ The Singular documentation for '%s' is given below.
continue
elif isinstance(a, Matrix_mpolynomial_dense):
ring2 = a.base_ring()
elif isinstance(a, list) or isinstance(a, tuple)\
or isinstance(a, Sequence_generic):
elif isinstance(a, (list, tuple, Sequence_generic)):
#TODO: catch exception, if recursion finds no ring
ring2 = self.common_ring(tuple(a), ring)
elif isinstance(a, Resolution):
Expand Down
2 changes: 1 addition & 1 deletion src/sage/matroids/utilities.py
Expand Up @@ -123,7 +123,7 @@ def setprint_s(X, toplevel=False):
sage: setprint_s(X, toplevel=True)
'abcd'
"""
if isinstance(X, frozenset) or isinstance(X, set):
if isinstance(X, (frozenset, set)):
return '{' + ', '.join(sorted(setprint_s(x) for x in X)) + '}'
elif isinstance(X, dict):
return '{' + ', '.join(sorted(setprint_s(key) + ': ' + setprint_s(val)
Expand Down
2 changes: 1 addition & 1 deletion src/sage/modular/cusps.py
Expand Up @@ -214,7 +214,7 @@ def __init__(self, a, b=None, parent=None, check=True):
self.__b = ZZ.zero()
return

if isinstance(a, Integer) or isinstance(a, Rational):
if isinstance(a, (Integer, Rational)):
r = a / ZZ(b)
elif is_InfinityElement(a):
self.__a = ZZ.one()
Expand Down
2 changes: 1 addition & 1 deletion src/sage/modular/modform_hecketriangle/analytic_type.py
Expand Up @@ -528,7 +528,7 @@ def _element_constructor_(self, element):

if isinstance(element, str):
element=[element]
if isinstance(element,list) or isinstance(element,tuple):
if isinstance(element, (list, tuple)):
element = Set(self._base_poset.order_ideal([self._base_poset(s) for s in element]))

return super(AnalyticType, self)._element_constructor_(element)
Expand Down
2 changes: 1 addition & 1 deletion src/sage/modular/modform_hecketriangle/subspace.py
Expand Up @@ -84,7 +84,7 @@ def ModularFormsSubSpace(*args, **kwargs):

generators = []
for arg in args:
if isinstance(arg, list) or isinstance(arg, tuple):
if isinstance(arg, (list, tuple)):
generators += arg
else:
generators.append(arg)
Expand Down
2 changes: 1 addition & 1 deletion src/sage/modules/vector_mod2_dense.pyx
Expand Up @@ -505,7 +505,7 @@ def unpickle_v0(parent, entries, degree, is_immutable):
cdef int xi

for i from 0 <= i < degree:
if isinstance(entries[i], IntegerMod_int) or isinstance(entries[i], int) or isinstance(entries[i], Integer):
if isinstance(entries[i], (IntegerMod_int, int, Integer)):
xi = entries[i]
mzd_write_bit(v._entries, 0, i, xi%2)
else:
Expand Down
2 changes: 1 addition & 1 deletion src/sage/numerical/mip.pyx
Expand Up @@ -1004,7 +1004,7 @@ cdef class MixedIntegerLinearProgram(SageObject):
indices = list(xrange(b.nrows()))

# Only one constraint
if isinstance(indices, int) or isinstance(indices, Integer):
if isinstance(indices, (int, Integer)):
lb, ub = b.row_bounds(indices)
return (lb, b.row(indices), ub)

Expand Down
6 changes: 3 additions & 3 deletions src/sage/numerical/optimize.py
Expand Up @@ -542,8 +542,8 @@ def minimize_constrained(func,cons,x0,gradient=None,algorithm='default', **args)
else:
f = func

if isinstance(cons,list):
if isinstance(cons[0], tuple) or isinstance(cons[0], list) or cons[0] is None:
if isinstance(cons, list):
if isinstance(cons[0], (tuple, list)) or cons[0] is None:
if gradient is not None:
if algorithm == 'l-bfgs-b':
min = optimize.fmin_l_bfgs_b(f, x0, gradient, bounds=cons, iprint=-1, **args)[0]
Expand All @@ -554,7 +554,7 @@ def minimize_constrained(func,cons,x0,gradient=None,algorithm='default', **args)
min = optimize.fmin_l_bfgs_b(f, x0, approx_grad=True, bounds=cons, iprint=-1, **args)[0]
else:
min = optimize.fmin_tnc(f, x0, approx_grad=True, bounds=cons, messages=0, **args)[0]
elif isinstance(cons[0], function_type) or isinstance(cons[0], Expression):
elif isinstance(cons[0], (function_type, Expression)):
min = optimize.fmin_cobyla(f, x0, cons, **args)
elif isinstance(cons, function_type) or isinstance(cons, Expression):
min = optimize.fmin_cobyla(f, x0, cons, **args)
Expand Down
2 changes: 1 addition & 1 deletion src/sage/rings/complex_mpc.pyx
Expand Up @@ -846,7 +846,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
return
elif isinstance(z, sage.libs.pari.all.pari_gen):
real, imag = z.real(), z.imag()
elif isinstance(z, list) or isinstance(z, tuple):
elif isinstance(z, (list, tuple)):
real, imag = z
elif isinstance(z, complex):
real, imag = z.real, z.imag
Expand Down
2 changes: 1 addition & 1 deletion src/sage/rings/complex_mpfr.pyx
Expand Up @@ -958,7 +958,7 @@ cdef class ComplexNumber(sage.structure.element.FieldElement):
real, imag = (<ComplexNumber>real).real(), (<ComplexNumber>real).imag()
elif isinstance(real, sage.libs.pari.all.pari_gen):
real, imag = real.real(), real.imag()
elif isinstance(real, list) or isinstance(real, tuple):
elif isinstance(real, (list, tuple)):
re, imag = real
real = re
elif isinstance(real, complex):
Expand Down
2 changes: 1 addition & 1 deletion src/sage/rings/convert/mpfi.pyx
Expand Up @@ -86,7 +86,7 @@ cdef int mpfi_set_sage(mpfi_ptr re, mpfi_ptr im, x, field, int base) except -1:
mpfi_set_sage(re, NULL, x[0], field, base)
mpfi_set_sage(im, NULL, x[1], field, base)
return 0
if isinstance(x, list) or isinstance(x, tuple):
if isinstance(x, (list, tuple)):
# Interpret entries in x as endpoints of interval
if len(x) != 2:
raise TypeError("list defining an interval must have length 2")
Expand Down
4 changes: 1 addition & 3 deletions src/sage/rings/finite_rings/element_ntl_gf2e.pyx
Expand Up @@ -308,9 +308,7 @@ cdef class Cache_ntl_gf2e(Cache_base):

if is_IntegerMod(e):
e = e.lift()
if isinstance(e, int) or \
isinstance(e, Integer) or \
isinstance(e, long):
if isinstance(e, (int, Integer)):
GF2E_conv_long(res.x,int(e&1))
return res

Expand Down
2 changes: 1 addition & 1 deletion src/sage/rings/polynomial/groebner_fan.py
Expand Up @@ -1331,7 +1331,7 @@ def render(self, file=None, larger=False, shift=0, rgbcolor=(0, 0, 0),
r_lines = r_lines + line(x, rgbcolor=rgbcolor)
if polyfill:
vals = [polyfill(q) for q in self.reduced_groebner_bases()]
if isinstance(vals[0], list) or isinstance(vals[0], tuple):
if isinstance(vals[0], (list, tuple)):
if scale_colors:
vmins = [min([q[i] for q in vals]) for i in (0, 1, 2)]
vmaxs = [max([q[i] for q in vals]) for i in (0, 1, 2)]
Expand Down
2 changes: 1 addition & 1 deletion src/sage/rings/polynomial/pbori/pbori.pyx
Expand Up @@ -8165,7 +8165,7 @@ cdef class PolynomialFactory:
elif isinstance(ring, BooleanPolynomialRing):
return (<BooleanPolynomialRing>ring).coerce(arg)
else:
if isinstance(arg, int) or isinstance(arg, Integer):
if isinstance(arg, (int, Integer)):
return new_BP_from_PBPoly(self._ring,
self._factory(<long>arg))

Expand Down
2 changes: 1 addition & 1 deletion src/sage/rings/polynomial/polynomial_zmod_flint.pyx
Expand Up @@ -100,7 +100,7 @@ cdef class Polynomial_zmod_flint(Polynomial_template):
"""
cdef long nlen

if isinstance(x, list) or isinstance(x, tuple):
if isinstance(x, (list, tuple)):
k = parent._base
if check:
lst = [k(i) for i in x]
Expand Down
2 changes: 1 addition & 1 deletion src/sage/rings/polynomial/polynomial_zz_pex.pyx
Expand Up @@ -138,7 +138,7 @@ cdef class Polynomial_ZZ_pEX(Polynomial_template):
if isinstance(x, Polynomial):
x = x.list()

if isinstance(x, list) or isinstance(x, tuple):
if isinstance(x, (list, tuple)):
Polynomial.__init__(self, parent, is_gen=is_gen)
(<Polynomial_template>self)._cparent = get_cparent(parent)
celement_construct(&self.x, (<Polynomial_template>self)._cparent)
Expand Down
8 changes: 5 additions & 3 deletions src/sage/rings/polynomial/term_order.py
Expand Up @@ -706,7 +706,7 @@ def __init__(self, name='lex', n=0, force=False):
name = name.lower()
else:
try:
if not isinstance(name, (tuple,list)):
if not isinstance(name, (tuple, list)):
name = name.list() # name may be a matrix
name = tuple(name)
except Exception:
Expand Down Expand Up @@ -766,7 +766,8 @@ def __init__(self, name='lex', n=0, force=False):
self._macaulay2_str = "{" + ",".join(macaulay2_str) + "}"
self._magma_str = "" # Magma does not support block order
self._blocks = tuple(blocks)
elif isinstance(name, str) and not (isinstance(n, tuple) or isinstance(n,list)): # string representation of simple or block orders
elif isinstance(name, str) and not isinstance(n, (tuple, list)):
# string representation of simple or block orders
if force:
self._length = n
self._name = name
Expand Down Expand Up @@ -817,7 +818,8 @@ def __init__(self, name='lex', n=0, force=False):
if n and length != n:
raise ValueError("term order length does not match the number of generators")
self.__copy(TermOrder('block', blocks))
elif isinstance(name, str) and (isinstance(n, tuple) or isinstance(n,list)): # weighted degree term orders
elif isinstance(name, str) and isinstance(n, (tuple, list)):
# weighted degree term orders
if name not in print_name_mapping.keys() and name not in singular_name_mapping.values() and not force:
raise ValueError("unknown term order {!r}".format(name))
weights = tuple(int(w) for w in n) # n is a tuple of weights
Expand Down
10 changes: 5 additions & 5 deletions src/sage/sandpiles/sandpile.py
Expand Up @@ -593,7 +593,7 @@ def __init__(self, g, sink=None):
TypeError: ...__init__() got an unexpected keyword argument 'weighted'
"""
# set graph name
if isinstance(g, Graph) or isinstance(g, DiGraph):
if isinstance(g, (Graph, DiGraph)):
name = g.name()
if name == '':
name = 'sandpile graph'
Expand All @@ -612,7 +612,7 @@ def __init__(self, g, sink=None):
elif isinstance(g, dict) and isinstance(next(iter(g.values())), list):
processed_g = {i: dict(Counter(g[i])) for i in g}
g = processed_g
elif isinstance(g, Graph) or isinstance(g, DiGraph):
elif isinstance(g, (Graph, DiGraph)):
if not g.weighted():
h = g.to_dictionary(multiple_edges=True)
g = {i: dict(Counter(h[i])) for i in h}
Expand Down Expand Up @@ -2254,7 +2254,7 @@ def markov_chain(self,state, distrib=None):
st = deepcopy(state)
V = self.vertices()
n = len(V)
if isinstance(st,list):
if isinstance(st, list):
if len(st)==self.num_verts()-1:
st = SandpileConfig(self,st)
elif len(st)==self.num_verts():
Expand All @@ -2264,7 +2264,7 @@ def markov_chain(self,state, distrib=None):
if distrib is None: # default = uniform distribution
distrib = [QQ.one() / n] * n
X = GeneralDiscreteDistribution(distrib)
if isinstance(st,SandpileConfig):
if isinstance(st, SandpileConfig):
while True:
i = X.get_random_element()
if V[i] != self.sink():
Expand Down Expand Up @@ -2963,7 +2963,7 @@ def __init__(self, S, c):
{1: 2, 2: 2, 3: 0}
"""
if len(c)==S.num_verts()-1:
if isinstance(c, dict) or isinstance(c, SandpileConfig):
if isinstance(c, (dict, SandpileConfig)):
dict.__init__(self,c)
elif isinstance(c, list):
c.reverse()
Expand Down
2 changes: 1 addition & 1 deletion src/sage/schemes/berkovich/berkovich_cp_element.py
Expand Up @@ -88,7 +88,7 @@ def __init__(self, parent, center, radius=None, power=None, prec=20, space_type=
self._type = None

# if radius is a list or a tuple, this is a type 4 point
if isinstance(radius, list) or isinstance(radius, tuple):
if isinstance(radius, (list, tuple)):
if error_check:
if not (isinstance(center, list) or isinstance(center, tuple)):
raise TypeError("center was passed a list but radius was not a list")
Expand Down
2 changes: 1 addition & 1 deletion src/sage/schemes/plane_conics/con_rational_field.py
Expand Up @@ -230,7 +230,7 @@ def is_locally_solvable(self, p) -> bool:
return True
a = -abc[0] / abc[2]
b = -abc[1] / abc[2]
if isinstance(p, sage.rings.abc.RealField) or isinstance(p, InfinityElement):
if isinstance(p, (sage.rings.abc.RealField, InfinityElement)):
p = -1
elif isinstance(p, Map) and p.category_for().is_subcategory(Rings()):
# p is a morphism of Rings
Expand Down
2 changes: 1 addition & 1 deletion src/sage/stats/time_series.pyx
Expand Up @@ -131,7 +131,7 @@ cdef class TimeSeries:
if isinstance(values, (int, long, Integer)):
self._length = values
values = None
elif isinstance(values, Vector_real_double_dense) or isinstance(values, cnumpy.ndarray):
elif isinstance(values, (Vector_real_double_dense, cnumpy.ndarray)):
if isinstance(values, Vector_real_double_dense):
np = values._vector_numpy
else:
Expand Down
2 changes: 1 addition & 1 deletion src/sage/structure/parent.pyx
Expand Up @@ -1740,7 +1740,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject):
raise ValueError("Map's codomain must be self")
self._convert_from_list.append(mor)
self._convert_from_hash.set(mor.domain(), mor)
elif isinstance(mor, Parent) or isinstance(mor, type):
elif isinstance(mor, (Parent, type)):
t = mor
mor = self._generic_convert_map(mor)
self._convert_from_list.append(mor)
Expand Down

0 comments on commit fd6379f

Please sign in to comment.