From 7431cfd27f3506f68c18f87e0de7dbf2c25e0e3c Mon Sep 17 00:00:00 2001 From: Oscar Gustafsson Date: Wed, 22 Sep 2021 19:01:41 +0200 Subject: [PATCH] Improved type checking --- sympy/assumptions/refine.py | 2 +- sympy/categories/baseclasses.py | 2 +- sympy/categories/diagram_drawing.py | 2 +- sympy/combinatorics/graycode.py | 2 +- sympy/combinatorics/subsets.py | 2 +- sympy/concrete/expr_with_limits.py | 6 +++--- sympy/concrete/products.py | 2 +- sympy/concrete/summations.py | 2 +- sympy/core/compatibility.py | 2 +- sympy/core/containers.py | 2 +- sympy/core/evalf.py | 8 ++++---- sympy/core/numbers.py | 10 +++++----- sympy/crypto/crypto.py | 2 +- sympy/functions/elementary/trigonometric.py | 8 ++++---- sympy/geometry/entity.py | 2 +- sympy/holonomic/holonomic.py | 4 ++-- sympy/integrals/integrals.py | 2 +- sympy/integrals/manualintegrate.py | 2 +- sympy/integrals/meijerint.py | 4 ++-- sympy/integrals/rationaltools.py | 13 ++++++------- sympy/integrals/risch.py | 2 +- sympy/integrals/rubi/rubimain.py | 2 +- sympy/liealgebras/cartan_type.py | 4 ++-- sympy/matrices/common.py | 2 +- sympy/matrices/eigen.py | 19 +++++++++---------- sympy/matrices/matrices.py | 2 +- sympy/ntheory/factor_.py | 12 ++++++------ sympy/physics/mechanics/system.py | 4 ++-- sympy/physics/quantum/cg.py | 2 +- sympy/physics/quantum/circuitplot.py | 2 +- sympy/physics/quantum/circuitutils.py | 4 ++-- sympy/physics/quantum/represent.py | 4 ++-- sympy/physics/quantum/spin.py | 12 ++++++------ sympy/plotting/experimental_lambdify.py | 7 +++---- sympy/plotting/plot.py | 2 +- sympy/polys/densebasic.py | 4 ++-- sympy/polys/galoistools.py | 2 +- sympy/polys/numberfields.py | 2 +- sympy/polys/polyclasses.py | 1 + sympy/printing/maple.py | 9 +++------ sympy/sets/sets.py | 2 +- sympy/simplify/epathtools.py | 4 ++-- sympy/simplify/simplify.py | 2 +- sympy/solvers/ode/nonhomogeneous.py | 2 +- sympy/solvers/solvers.py | 2 +- sympy/stats/rv_interface.py | 2 +- sympy/stats/stochastic_process_types.py | 12 ++++++------ sympy/vector/implicitregion.py | 2 +- sympy/vector/parametricregion.py | 4 ++-- 49 files changed, 102 insertions(+), 107 deletions(-) diff --git a/sympy/assumptions/refine.py b/sympy/assumptions/refine.py index 146fbb31d34d..3b9d2828ab59 100644 --- a/sympy/assumptions/refine.py +++ b/sympy/assumptions/refine.py @@ -147,7 +147,7 @@ def refine_Pow(expr, assumptions): if ask(Q.odd(expr.exp), assumptions): return sign(expr.base) * abs(expr.base) ** expr.exp if isinstance(expr.exp, Rational): - if type(expr.base) is Pow: + if isinstance(expr.base, Pow): return abs(expr.base.base) ** (expr.base.exp * expr.exp) if expr.base is S.NegativeOne: diff --git a/sympy/categories/baseclasses.py b/sympy/categories/baseclasses.py index f005787111e0..038cfed70df9 100644 --- a/sympy/categories/baseclasses.py +++ b/sympy/categories/baseclasses.py @@ -749,7 +749,7 @@ def __new__(cls, *args): for morphism in premises_arg: objects |= FiniteSet(morphism.domain, morphism.codomain) Diagram._add_morphism_closure(premises, morphism, empty) - elif isinstance(premises_arg, dict) or isinstance(premises_arg, Dict): + elif isinstance(premises_arg, (dict, Dict)): # The user has supplied a dictionary of morphisms and # their properties. for morphism, props in premises_arg.items(): diff --git a/sympy/categories/diagram_drawing.py b/sympy/categories/diagram_drawing.py index cfd9692e1791..301ab0c4c800 100644 --- a/sympy/categories/diagram_drawing.py +++ b/sympy/categories/diagram_drawing.py @@ -842,7 +842,7 @@ def group_to_finiteset(group): # should be converted to a FiniteSet, because that is what the # following code expects. - if isinstance(groups, dict) or isinstance(groups, Dict): + if isinstance(groups, (dict, Dict)): finiteset_groups = {} for group, local_hints in groups.items(): finiteset_group = group_to_finiteset(group) diff --git a/sympy/combinatorics/graycode.py b/sympy/combinatorics/graycode.py index 4e42e50a87c5..4b1ddb8d5494 100644 --- a/sympy/combinatorics/graycode.py +++ b/sympy/combinatorics/graycode.py @@ -281,7 +281,7 @@ def current(self): '100' """ rv = self._current or '0' - if type(rv) is not str: + if not isinstance(rv, str): rv = bin(rv)[2:] return rv.rjust(self.n, '0') diff --git a/sympy/combinatorics/subsets.py b/sympy/combinatorics/subsets.py index 9ce3c435ff81..57bec6a326f7 100644 --- a/sympy/combinatorics/subsets.py +++ b/sympy/combinatorics/subsets.py @@ -507,7 +507,7 @@ def bitlist_from_subset(self, subset, superset): subset_from_bitlist """ bitlist = ['0'] * len(superset) - if type(subset) is Subset: + if isinstance(subset, Subset): subset = subset.subset for i in Subset.subset_indices(subset, superset): bitlist[i] = '1' diff --git a/sympy/concrete/expr_with_limits.py b/sympy/concrete/expr_with_limits.py index 653fd86a6d41..2d6093c2878f 100644 --- a/sympy/concrete/expr_with_limits.py +++ b/sympy/concrete/expr_with_limits.py @@ -164,7 +164,7 @@ class ExprWithLimits(Expr): def __new__(cls, function, *symbols, **assumptions): pre = _common_new(cls, function, *symbols, **assumptions) - if type(pre) is tuple: + if isinstance(pre, tuple): function, limits, _ = pre else: return pre @@ -358,7 +358,7 @@ def _eval_subs(self, old, new): if len(xab[0].free_symbols.intersection(old.free_symbols)) != 0: sub_into_func = False break - if isinstance(old, AppliedUndef) or isinstance(old, UndefinedFunction): + if isinstance(old, (AppliedUndef, UndefinedFunction)): sy2 = set(self.variables).intersection(set(new.atoms(Symbol))) sy1 = set(self.variables).intersection(set(old.args)) if not sy2.issubset(sy1): @@ -497,7 +497,7 @@ class AddWithLimits(ExprWithLimits): def __new__(cls, function, *symbols, **assumptions): pre = _common_new(cls, function, *symbols, **assumptions) - if type(pre) is tuple: + if isinstance(pre, tuple): function, limits, orientation = pre else: return pre diff --git a/sympy/concrete/products.py b/sympy/concrete/products.py index 06d61b6a73ff..0b2d753d1e65 100644 --- a/sympy/concrete/products.py +++ b/sympy/concrete/products.py @@ -255,7 +255,7 @@ def doit(self, **hints): if reps: undo = {v: k for k, v in reps.items()} did = self.xreplace(reps).doit(**hints) - if type(did) is tuple: # when separate=True + if isinstance(did, tuple): # when separate=True did = tuple([i.xreplace(undo) for i in did]) else: did = did.xreplace(undo) diff --git a/sympy/concrete/summations.py b/sympy/concrete/summations.py index 40a709d1faf5..821fbdcf34a5 100644 --- a/sympy/concrete/summations.py +++ b/sympy/concrete/summations.py @@ -213,7 +213,7 @@ def doit(self, **hints): if reps: undo = {v: k for k, v in reps.items()} did = self.xreplace(reps).doit(**hints) - if type(did) is tuple: # when separate=True + if isinstance(did, tuple): # when separate=True did = tuple([i.xreplace(undo) for i in did]) elif did is not None: did = did.xreplace(undo) diff --git a/sympy/core/compatibility.py b/sympy/core/compatibility.py index 356cb060e781..279b73a5f639 100644 --- a/sympy/core/compatibility.py +++ b/sympy/core/compatibility.py @@ -297,7 +297,7 @@ def as_int(n, strict=True): """ if strict: try: - if type(n) is bool: + if isinstance(n, bool): raise TypeError return operator.index(n) except TypeError: diff --git a/sympy/core/containers.py b/sympy/core/containers.py index 770905e6a71c..847af06eaec3 100644 --- a/sympy/core/containers.py +++ b/sympy/core/containers.py @@ -177,7 +177,7 @@ def tuple_wrapper(method): def wrap_tuples(*args, **kw_args): newargs = [] for arg in args: - if type(arg) is tuple: + if isinstance(arg, tuple): newargs.append(Tuple(*arg)) else: newargs.append(arg) diff --git a/sympy/core/evalf.py b/sympy/core/evalf.py index 7546422d1256..dbb8602d74cd 100644 --- a/sympy/core/evalf.py +++ b/sympy/core/evalf.py @@ -173,7 +173,7 @@ def scaled_zero(mag, sign=1): >>> Float(scaled_zero(ok), p) -0.e+30 """ - if type(mag) is tuple and len(mag) == 4 and iszero(mag, scaled=True): + if isinstance(mag, tuple) and len(mag) == 4 and iszero(mag, scaled=True): return (mag[0][0],) + mag[1:] elif isinstance(mag, SYMPY_INTS): if sign not in [-1, 1]: @@ -189,7 +189,7 @@ def scaled_zero(mag, sign=1): def iszero(mpf, scaled=False): if not scaled: return not mpf or not mpf[1] and not mpf[-1] - return mpf and type(mpf[0]) is list and mpf[1] == mpf[-1] == 1 + return mpf and isinstance(mpf[0], list) and mpf[1] == mpf[-1] == 1 def complex_accuracy(result): @@ -915,9 +915,9 @@ def evalf_piecewise(expr, prec, options): del newopts['subs'] if hasattr(expr, 'func'): return evalf(expr, prec, newopts) - if type(expr) == float: + if isinstance(expr, float): return evalf(Float(expr), prec, newopts) - if type(expr) == int: + if isinstance(expr, int): return evalf(Integer(expr), prec, newopts) # We still have undefined symbols diff --git a/sympy/core/numbers.py b/sympy/core/numbers.py index 291241953ada..5195be3a6605 100644 --- a/sympy/core/numbers.py +++ b/sympy/core/numbers.py @@ -1152,7 +1152,7 @@ def __new__(cls, num, dps=None, prec=None, precision=None): else: raise ValueError("unexpected decimal value %s" % str(num)) elif isinstance(num, tuple) and len(num) in (3, 4): - if type(num[1]) is str: + if isinstance(num[1], str): # it's a hexadecimal (coming from a pickled object) num = list(num) # If we're loading an object pickled in Python 2 into @@ -1952,7 +1952,7 @@ def __gt__(self, other): rv = self._Rrel(other, '__lt__') if rv is None: rv = self, other - elif not type(rv) is tuple: + elif not isinstance(rv, tuple): return rv return Expr.__gt__(*rv) @@ -1960,7 +1960,7 @@ def __ge__(self, other): rv = self._Rrel(other, '__le__') if rv is None: rv = self, other - elif not type(rv) is tuple: + elif not isinstance(rv, tuple): return rv return Expr.__ge__(*rv) @@ -1968,7 +1968,7 @@ def __lt__(self, other): rv = self._Rrel(other, '__gt__') if rv is None: rv = self, other - elif not type(rv) is tuple: + elif not isinstance(rv, tuple): return rv return Expr.__lt__(*rv) @@ -1976,7 +1976,7 @@ def __le__(self, other): rv = self._Rrel(other, '__ge__') if rv is None: rv = self, other - elif not type(rv) is tuple: + elif not isinstance(rv, tuple): return rv return Expr.__le__(*rv) diff --git a/sympy/crypto/crypto.py b/sympy/crypto/crypto.py index c121a7dec9af..fafaed89dc30 100644 --- a/sympy/crypto/crypto.py +++ b/sympy/crypto/crypto.py @@ -65,7 +65,7 @@ def AZ(s=None): """ if not s: return uppercase - t = type(s) is str + t = isinstance(s, str) if t: s = [s] rv = [check_and_join(i.upper().split(), uppercase, filter=True) diff --git a/sympy/functions/elementary/trigonometric.py b/sympy/functions/elementary/trigonometric.py index 8051c160e16d..80375c86d6cd 100644 --- a/sympy/functions/elementary/trigonometric.py +++ b/sympy/functions/elementary/trigonometric.py @@ -401,7 +401,7 @@ def _eval_nseries(self, x, n, logx, cdir=0): def _eval_rewrite_as_exp(self, arg, **kwargs): I = S.ImaginaryUnit - if isinstance(arg, TrigonometricFunction) or isinstance(arg, HyperbolicFunction): + if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)): arg = arg.func(arg.args[0]).rewrite(exp) return (exp(arg*I) - exp(-arg*I))/(2*I) @@ -734,7 +734,7 @@ def _eval_nseries(self, x, n, logx, cdir=0): def _eval_rewrite_as_exp(self, arg, **kwargs): I = S.ImaginaryUnit - if isinstance(arg, TrigonometricFunction) or isinstance(arg, HyperbolicFunction): + if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)): arg = arg.func(arg.args[0]).rewrite(exp) return (exp(arg*I) + exp(-arg*I))/2 @@ -1222,7 +1222,7 @@ def _eval_expand_trig(self, **hints): def _eval_rewrite_as_exp(self, arg, **kwargs): I = S.ImaginaryUnit - if isinstance(arg, TrigonometricFunction) or isinstance(arg, HyperbolicFunction): + if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)): arg = arg.func(arg.args[0]).rewrite(exp) neg_exp, pos_exp = exp(-arg*I), exp(arg*I) return I*(neg_exp - pos_exp)/(neg_exp + pos_exp) @@ -1498,7 +1498,7 @@ def as_real_imag(self, deep=True, **hints): def _eval_rewrite_as_exp(self, arg, **kwargs): I = S.ImaginaryUnit - if isinstance(arg, TrigonometricFunction) or isinstance(arg, HyperbolicFunction): + if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)): arg = arg.func(arg.args[0]).rewrite(exp) neg_exp, pos_exp = exp(-arg*I), exp(arg*I) return I*(pos_exp + neg_exp)/(pos_exp - neg_exp) diff --git a/sympy/geometry/entity.py b/sympy/geometry/entity.py index 80c3db21d93f..ac2dc86b6c5f 100644 --- a/sympy/geometry/entity.py +++ b/sympy/geometry/entity.py @@ -294,7 +294,7 @@ def encloses(self, o): return self.encloses_point(o) elif isinstance(o, Segment): return all(self.encloses_point(x) for x in o.points) - elif isinstance(o, Ray) or isinstance(o, Line): + elif isinstance(o, (Ray, Line)): return False elif isinstance(o, Ellipse): return self.encloses_point(o.center) and \ diff --git a/sympy/holonomic/holonomic.py b/sympy/holonomic/holonomic.py index c28694d2bc65..eaf66024c58a 100644 --- a/sympy/holonomic/holonomic.py +++ b/sympy/holonomic/holonomic.py @@ -2185,7 +2185,7 @@ def from_hyper(func, x0=0, evalf=False): simp = hyperexpand(func) - if isinstance(simp, Infinity) or isinstance(simp, NegativeInfinity): + if simp in (Infinity, NegativeInfinity): return HolonomicFunction(sol, x).composition(z) def _find_conditions(simp, x, x0, order, evalf=False): @@ -2271,7 +2271,7 @@ def from_meijerg(func, x0=0, evalf=False, initcond=True, domain=QQ): simp = hyperexpand(func) - if isinstance(simp, Infinity) or isinstance(simp, NegativeInfinity): + if simp in (Infinity, NegativeInfinity): return HolonomicFunction(sol, x).composition(z) def _find_conditions(simp, x, x0, order, evalf=False): diff --git a/sympy/integrals/integrals.py b/sympy/integrals/integrals.py index c2722e73d1f5..d9c7a5acbcaf 100644 --- a/sympy/integrals/integrals.py +++ b/sympy/integrals/integrals.py @@ -484,7 +484,7 @@ def doit(self, **hints): if reps: undo = {v: k for k, v in reps.items()} did = self.xreplace(reps).doit(**hints) - if type(did) is tuple: # when separate=True + if isinstance(did, tuple): # when separate=True did = tuple([i.xreplace(undo) for i in did]) else: did = did.xreplace(undo) diff --git a/sympy/integrals/manualintegrate.py b/sympy/integrals/manualintegrate.py index 0435d394ba50..4ea1dab096e7 100644 --- a/sympy/integrals/manualintegrate.py +++ b/sympy/integrals/manualintegrate.py @@ -682,7 +682,7 @@ def make_second_step(steps, integrand): def trig_rule(integral): integrand, symbol = integral - if isinstance(integrand, sympy.sin) or isinstance(integrand, sympy.cos): + if isinstance(integrand, (sympy.sin, sympy.cos)): arg = integrand.args[0] if not isinstance(arg, sympy.Symbol): diff --git a/sympy/integrals/meijerint.py b/sympy/integrals/meijerint.py index 64cc11a151cc..936de672125f 100644 --- a/sympy/integrals/meijerint.py +++ b/sympy/integrals/meijerint.py @@ -1663,7 +1663,7 @@ def meijerint_indefinite(f, x): rv = meijerint_indefinite( _rewrite_hyperbolics_as_exp(f), x) if rv: - if not type(rv) is list: + if not isinstance(rv, list): return collect(factor_terms(rv), rv.atoms(exp)) results.extend(rv) if results: @@ -1890,7 +1890,7 @@ def meijerint_definite(f, x, a, b): rv = meijerint_definite( _rewrite_hyperbolics_as_exp(f_), x_, a_, b_) if rv: - if not type(rv) is list: + if not isinstance(rv, list): rv = (collect(factor_terms(rv[0]), rv[0].atoms(exp)),) + rv[1:] return rv results.extend(rv) diff --git a/sympy/integrals/rationaltools.py b/sympy/integrals/rationaltools.py index c55967bd05ea..aaa9a47047ef 100644 --- a/sympy/integrals/rationaltools.py +++ b/sympy/integrals/rationaltools.py @@ -39,10 +39,10 @@ def ratint(f, x, **flags): sympy.integrals.rationaltools.ratint_ratpart """ - if type(f) is not tuple: - p, q = f.as_numer_denom() - else: + if isinstance(f, tuple): p, q = f + else: + p, q = f.as_numer_denom() p, q = Poly(p, x, composite=False, field=True), Poly(q, x, composite=False, field=True) @@ -78,12 +78,11 @@ def ratint(f, x, **flags): real = flags.get('real') if real is None: - if type(f) is not tuple: - atoms = f.atoms() - else: + if isinstance(f, tuple): p, q = f - atoms = p.atoms() | q.atoms() + else: + atoms = f.atoms() for elt in atoms - {x}: if not elt.is_extended_real: diff --git a/sympy/integrals/risch.py b/sympy/integrals/risch.py index 0835a1b4f36b..a56e26578b0f 100644 --- a/sympy/integrals/risch.py +++ b/sympy/integrals/risch.py @@ -820,7 +820,7 @@ def frac_in(f, t, *, cancel=False, **kwargs): where fa and fd are either basic expressions or Polys, and f == fa/fd. **kwargs are applied to Poly. """ - if type(f) is tuple: + if isinstance(f, tuple): fa, fd = f f = fa.as_expr()/fd.as_expr() fa, fd = f.as_expr().as_numer_denom() diff --git a/sympy/integrals/rubi/rubimain.py b/sympy/integrals/rubi/rubimain.py index 5dae06fd54a2..ed1c44aa1930 100644 --- a/sympy/integrals/rubi/rubimain.py +++ b/sympy/integrals/rubi/rubimain.py @@ -193,7 +193,7 @@ def rubi_integrate(expr, var, showsteps=False): expr = expr.replace(sym_exp, rubi_exp) expr = process_trig(expr) expr = rubi_powsimp(expr) - if isinstance(expr, (int, Integer)) or isinstance(expr, (float, Float)): + if isinstance(expr, (int, Integer, float, Float)): return S(expr)*var if isinstance(expr, Add): results = 0 diff --git a/sympy/liealgebras/cartan_type.py b/sympy/liealgebras/cartan_type.py index f2f84fa18cc7..35590b2b23aa 100644 --- a/sympy/liealgebras/cartan_type.py +++ b/sympy/liealgebras/cartan_type.py @@ -7,9 +7,9 @@ class CartanType_generator(Basic): """ def __call__(self, *args): c = args[0] - if type(c) == list: + if isinstance(c, list): letter, n = c[0], int(c[1]) - elif type(c) == str: + elif isinstance(c, str): letter, n = c[0], int(c[1:]) else: raise TypeError("Argument must be a string (e.g. 'A3') or a list (e.g. ['A', 3])") diff --git a/sympy/matrices/common.py b/sympy/matrices/common.py index 236ce456a9b5..7e441b1d0094 100644 --- a/sympy/matrices/common.py +++ b/sympy/matrices/common.py @@ -3234,7 +3234,7 @@ def _matrixify(mat): def a2idx(j, n=None): """Return integer after making positive and validating against n.""" - if type(j) is not int: + if not isinstance(j, int): jindex = getattr(j, '__index__', None) if jindex is not None: j = jindex() diff --git a/sympy/matrices/eigen.py b/sympy/matrices/eigen.py index 227c62d6f1ce..310c2603620a 100644 --- a/sympy/matrices/eigen.py +++ b/sympy/matrices/eigen.py @@ -612,14 +612,14 @@ def _bidiagonal_decomposition(M, upper=True): """ - if type(upper) is not bool: + if not isinstance(upper, bool): raise ValueError("upper must be a boolean") - if not upper: - X = _bidiagonal_decmp_hholder(M.H) - return X[2].H, X[1].H, X[0].H + if upper: + return _bidiagonal_decmp_hholder(M) - return _bidiagonal_decmp_hholder(M) + X = _bidiagonal_decmp_hholder(M.H) + return X[2].H, X[1].H, X[0].H def _bidiagonalize(M, upper=True): @@ -642,13 +642,12 @@ def _bidiagonalize(M, upper=True): """ - if type(upper) is not bool: + if not isinstance(upper, bool): raise ValueError("upper must be a boolean") - if not upper: - return _eval_bidiag_hholder(M.H).H - - return _eval_bidiag_hholder(M) + if upper: + return _eval_bidiag_hholder(M) + return _eval_bidiag_hholder(M.H).H def _diagonalize(M, reals_only=False, sort=False, normalize=False): diff --git a/sympy/matrices/matrices.py b/sympy/matrices/matrices.py index a1c02363e7ba..522d00e68748 100644 --- a/sympy/matrices/matrices.py +++ b/sympy/matrices/matrices.py @@ -1194,7 +1194,7 @@ def _setitem(self, key, value): is_slice = isinstance(key, slice) i, j = key = self.key2ij(key) is_mat = isinstance(value, MatrixBase) - if type(i) is slice or type(j) is slice: + if isinstance(i, slice) or isinstance(j, slice): if is_mat: self.copyin_matrix(key, value) return diff --git a/sympy/ntheory/factor_.py b/sympy/ntheory/factor_.py index 0684a7acee53..de6ebc4f5ec4 100644 --- a/sympy/ntheory/factor_.py +++ b/sympy/ntheory/factor_.py @@ -170,20 +170,20 @@ def smoothness_p(n, m=-1, power=0, visual=None): if visual is not True and visual is not False: return d return smoothness_p(d, visual=False) - elif type(n) is not tuple: + elif not isinstance(n, tuple): facs = factorint(n, visual=False) if power: k = -1 else: k = 1 - if type(n) is not tuple: + if isinstance(n, tuple): + rv = n + else: rv = (m, sorted([(f, tuple([M] + list(smoothness(f + m)))) for f, M in [i for i in facs.items()]], key=lambda x: (x[1][k], x[0]))) - else: - rv = n if visual is False or (visual is not True) and (type(n) in [int, Mul]): return rv @@ -1132,7 +1132,7 @@ def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True, return factorlist factordict = {} - if visual and not isinstance(n, Mul) and not isinstance(n, dict): + if visual and not isinstance(n, (Mul, dict)): factordict = factorint(n, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose, visual=False) @@ -1141,7 +1141,7 @@ def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True, n.as_powers_dict().items()} elif isinstance(n, dict): factordict = n - if factordict and (isinstance(n, Mul) or isinstance(n, dict)): + if factordict and isinstance(n, (Mul, dict)): # check it for key in list(factordict.keys()): if isprime(key): diff --git a/sympy/physics/mechanics/system.py b/sympy/physics/mechanics/system.py index 4e11f54ee66e..aa63b4dc16ef 100644 --- a/sympy/physics/mechanics/system.py +++ b/sympy/physics/mechanics/system.py @@ -263,9 +263,9 @@ def __init__(self, coord_states, right_hand_side, speeds=None, # Change the body and loads iterables to tuples if they are not tuples # already - if type(bodies) != tuple and bodies is not None: + if not isinstance(bodies, tuple) and bodies is not None: bodies = tuple(bodies) - if type(loads) != tuple and loads is not None: + if not isinstance(loads, tuple) and loads is not None: loads = tuple(loads) self._bodies = bodies self._loads = loads diff --git a/sympy/physics/quantum/cg.py b/sympy/physics/quantum/cg.py index f2a8d808a289..5cb37d036394 100644 --- a/sympy/physics/quantum/cg.py +++ b/sympy/physics/quantum/cg.py @@ -728,7 +728,7 @@ def _cg_list(term): return (term,), 1, 1 cg = [] coeff = 1 - if not (isinstance(term, Mul) or isinstance(term, Pow)): + if not isinstance(term, (Mul, Pow)): raise NotImplementedError('term must be CG, Add, Mul or Pow') if isinstance(term, Pow) and sympify(term.exp).is_number: if sympify(term.exp).is_number: diff --git a/sympy/physics/quantum/circuitplot.py b/sympy/physics/quantum/circuitplot.py index 32a037242672..84eb02f70c91 100644 --- a/sympy/physics/quantum/circuitplot.py +++ b/sympy/physics/quantum/circuitplot.py @@ -141,7 +141,7 @@ def _plot_measured_wires(self): self._axes.add_line(line) # Also double any controlled lines off these wires for i,g in enumerate(self._gates()): - if isinstance(g, CGate) or isinstance(g, CGateS): + if isinstance(g, (CGate, CGateS)): wires = g.controls + g.targets for wire in wires: if wire in ismeasured and \ diff --git a/sympy/physics/quantum/circuitutils.py b/sympy/physics/quantum/circuitutils.py index b87726cf177d..26b1d412b744 100644 --- a/sympy/physics/quantum/circuitutils.py +++ b/sympy/physics/quantum/circuitutils.py @@ -300,7 +300,7 @@ def create_inverse_map(symb_to_real_map): ndx_map.update(new_map) inv_map = create_inverse_map(ndx_map) - elif isinstance(item, tuple) or isinstance(item, Tuple): + elif isinstance(item, (tuple, Tuple)): result = convert_to_symbolic_indices(item, qubit_map=ndx_map, start=cur_ndx, @@ -365,7 +365,7 @@ def convert_to_real_indices(seq, qubit_map): if isinstance(item, Gate): real_item = convert_to_real_indices(item.args, qubit_map) - elif isinstance(item, tuple) or isinstance(item, Tuple): + elif isinstance(item, (tuple, Tuple)): real_item = convert_to_real_indices(item, qubit_map) else: diff --git a/sympy/physics/quantum/represent.py b/sympy/physics/quantum/represent.py index 6a883864887c..a0d04957c0ad 100644 --- a/sympy/physics/quantum/represent.py +++ b/sympy/physics/quantum/represent.py @@ -192,13 +192,13 @@ def _represent_FooBasis(self, e, basis, **options) return A*B + B*A elif isinstance(expr, InnerProduct): return represent(Mul(expr.bra, expr.ket), **options) - elif not (isinstance(expr, Mul) or isinstance(expr, OuterProduct)): + elif not isinstance(expr, (Mul, OuterProduct)): # For numpy and scipy.sparse, we can only handle numerical prefactors. if format == 'numpy' or format == 'scipy.sparse': return _sympy_to_scalar(expr) return expr - if not (isinstance(expr, Mul) or isinstance(expr, OuterProduct)): + if not isinstance(expr, (Mul, OuterProduct)): raise TypeError('Mul expected, got: %r' % expr) if "index" in options: diff --git a/sympy/physics/quantum/spin.py b/sympy/physics/quantum/spin.py index ac0e97ab5535..a0bb5332b36a 100644 --- a/sympy/physics/quantum/spin.py +++ b/sympy/physics/quantum/spin.py @@ -131,7 +131,7 @@ def _apply_operator_JzKetCoupled(self, ket, **options): def _apply_operator_TensorProduct(self, tp, **options): # Uncoupling operator is only easily found for coordinate basis spin operators # TODO: add methods for uncoupling operators - if not (isinstance(self, JxOp) or isinstance(self, JyOp) or isinstance(self, JzOp)): + if not isinstance(self, (JxOp, JyOp, JzOp)): raise NotImplementedError result = [] for n in range(len(tp.args)): @@ -1359,13 +1359,13 @@ def __new__(cls, j, m, jn, *jcoupling): else: raise TypeError("CoupledSpinState only takes 3 or 4 arguments, got: %s" % (len(jcoupling) + 3) ) # Check arguments have correct form - if not (isinstance(jn, list) or isinstance(jn, tuple) or isinstance(jn, Tuple)): + if not isinstance(jn, (list, tuple, Tuple)): raise TypeError('jn must be Tuple, list or tuple, got %s' % jn.__class__.__name__) - if not (isinstance(jcoupling, list) or isinstance(jcoupling, tuple) or isinstance(jcoupling, Tuple)): + if not isinstance(jcoupling, (list, tuple, Tuple)): raise TypeError('jcoupling must be Tuple, list or tuple, got %s' % jcoupling.__class__.__name__) - if not all(isinstance(term, list) or isinstance(term, tuple) or isinstance(term, Tuple) for term in jcoupling): + if not all(isinstance(term, (list, tuple, Tuple)) for term in jcoupling): raise TypeError( 'All elements of jcoupling must be list, tuple or Tuple') if not len(jn) - 1 == len(jcoupling): @@ -2049,7 +2049,7 @@ def _uncouple(state, jn, jcoupling_list): elif isinstance(state, SpinState): if jn is None: raise ValueError("Must specify j-values for coupled state") - if not (isinstance(jn, list) or isinstance(jn, tuple)): + if not isinstance(jn, (list, tuple)): raise TypeError("jn must be list or tuple") if jcoupling_list is None: # Use default @@ -2057,7 +2057,7 @@ def _uncouple(state, jn, jcoupling_list): for i in range(1, len(jn)): jcoupling_list.append( (1, 1 + i, Add(*[jn[j] for j in range(i + 1)])) ) - if not (isinstance(jcoupling_list, list) or isinstance(jcoupling_list, tuple)): + if not isinstance(jcoupling_list, (list, tuple)): raise TypeError("jcoupling must be a list or tuple") if not len(jcoupling_list) == len(jn) - 1: raise ValueError("Must specify 2 fewer coupling terms than the number of j values") diff --git a/sympy/plotting/experimental_lambdify.py b/sympy/plotting/experimental_lambdify.py index 7f3cfe6df5ad..8e5ed9bd6e81 100644 --- a/sympy/plotting/experimental_lambdify.py +++ b/sympy/plotting/experimental_lambdify.py @@ -176,10 +176,9 @@ def __call__(self, args): if abs(result.imag) > 1e-7 * abs(result): return None return result.real - except (ZeroDivisionError, OverflowError, TypeError) as e: - if isinstance(e, ZeroDivisionError) or isinstance(e, OverflowError): - return None - + except (ZeroDivisionError, OverflowError): + return None + except TypeError as e: if self.failure: raise e diff --git a/sympy/plotting/plot.py b/sympy/plotting/plot.py index 6f521bb9a29a..769fcdc6a0c0 100644 --- a/sympy/plotting/plot.py +++ b/sympy/plotting/plot.py @@ -1374,7 +1374,7 @@ def _process_series(self, series, ax, parent): collection = ax.plot_surface(x, y, z, cmap=getattr(self.cm, 'viridis', self.cm.jet), rstride=1, cstride=1, linewidth=0.1) - if isinstance(s.surface_color, (float, int)) or isinstance(s.surface_color, Callable): + if isinstance(s.surface_color, (float, int, Callable)): color_array = s.get_color_array() color_array = color_array.reshape(color_array.size) collection.set_array(color_array) diff --git a/sympy/polys/densebasic.py b/sympy/polys/densebasic.py index 1caeb8f62901..96008b178523 100644 --- a/sympy/polys/densebasic.py +++ b/sympy/polys/densebasic.py @@ -311,7 +311,7 @@ def dmp_strip(f, u): def _rec_validate(f, g, i, K): """Recursive helper for :func:`dmp_validate`.""" - if type(g) is not list: + if not isinstance(g, list): if K is not None and not K.of_type(g): raise TypeError("%s in %s in not of type %s" % (g, f, K.dtype)) @@ -935,7 +935,7 @@ def dup_from_dict(f, K): n, h = max(f.keys()), [] - if type(n) is int: + if isinstance(n, int): for k in range(n, -1, -1): h.append(f.get(k, K.zero)) else: diff --git a/sympy/polys/galoistools.py b/sympy/polys/galoistools.py index 9bfbba685331..486a853fec22 100644 --- a/sympy/polys/galoistools.py +++ b/sympy/polys/galoistools.py @@ -644,7 +644,7 @@ def gf_expand(F, p, K): [4, 3, 0, 3, 0, 1, 4, 1] """ - if type(F) is tuple: + if isinstance(F, tuple): lc, F = F else: lc = K.one diff --git a/sympy/polys/numberfields.py b/sympy/polys/numberfields.py index b5c7d27d2a37..4903f88eca0c 100644 --- a/sympy/polys/numberfields.py +++ b/sympy/polys/numberfields.py @@ -1071,7 +1071,7 @@ def to_number_field(extension, theta=None, *, gen=None): else: extension = [extension] - if len(extension) == 1 and type(extension[0]) is tuple: + if len(extension) == 1 and isinstance(extension[0], tuple): return AlgebraicNumber(extension[0]) minpoly, coeffs = primitive_element(extension, gen, polys=True) diff --git a/sympy/polys/polyclasses.py b/sympy/polys/polyclasses.py index 348dc5ef747b..75f49b5c3d8b 100644 --- a/sympy/polys/polyclasses.py +++ b/sympy/polys/polyclasses.py @@ -146,6 +146,7 @@ class DMP(PicklableWithSlots, CantSympify): def __init__(self, rep, dom, lev=None, ring=None): if lev is not None: + # Not possible to check with isinstance if type(rep) is dict: rep = dmp_from_dict(rep, lev, dom) elif type(rep) is not list: diff --git a/sympy/printing/maple.py b/sympy/printing/maple.py index 5fb11b637315..5bd8ccfbb305 100644 --- a/sympy/printing/maple.py +++ b/sympy/printing/maple.py @@ -206,7 +206,7 @@ def _print_SparseMatrix(self, expr): return self._get_matrix(expr, sparse=True) def _print_Identity(self, expr): - if isinstance(expr.rows, Integer) or isinstance(expr.rows, IntegerConstant): + if isinstance(expr.rows, (Integer, IntegerConstant)): return self._print(sympy.SparseMatrix(expr)) else: return "Matrix({var_size}, shape = identity)".format(var_size=self._print(expr.rows)) @@ -215,11 +215,8 @@ def _print_MatMul(self, expr): PREC=precedence(expr) _fact_list = list(expr.args) _const = None - if not ( - isinstance(_fact_list[0], sympy.MatrixBase) or isinstance( - _fact_list[0], sympy.MatrixExpr) or isinstance( - _fact_list[0], sympy.MatrixSlice) or isinstance( - _fact_list[0], sympy.MatrixSymbol)): + if not isinstance(_fact_list[0], (sympy.MatrixBase, sympy.MatrixExpr, + sympy.MatrixSlice, sympy.MatrixSymbol)): _const, _fact_list = _fact_list[0], _fact_list[1:] if _const is None or _const == 1: diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py index 929e78ba8ac1..b0cb7ec9152b 100644 --- a/sympy/sets/sets.py +++ b/sympy/sets/sets.py @@ -200,7 +200,7 @@ def _complement(self, other): return Union(*overlaps) elif isinstance(other, Interval): - if isinstance(self, Interval) or isinstance(self, FiniteSet): + if isinstance(self, (Interval, FiniteSet)): return Intersection(other, self.complement(S.Reals)) elif isinstance(other, Union): diff --git a/sympy/simplify/epathtools.py b/sympy/simplify/epathtools.py index a62f693e04bd..3fa59ac34ba2 100644 --- a/sympy/simplify/epathtools.py +++ b/sympy/simplify/epathtools.py @@ -195,7 +195,7 @@ def _apply(path, expr, func): args = list(args) if span is not None: - if type(span) == slice: + if isinstance(span, slice): indices = range(*span.indices(len(args))) else: indices = [span] @@ -262,7 +262,7 @@ def _select(path, expr): return if span is not None: - if type(span) == slice: + if isinstance(span, slice): args = args[span] else: try: diff --git a/sympy/simplify/simplify.py b/sympy/simplify/simplify.py index 3db9389d2c2f..ae6c4c51ed6a 100644 --- a/sympy/simplify/simplify.py +++ b/sympy/simplify/simplify.py @@ -803,7 +803,7 @@ def sum_combine(s_t): for j, s_term2 in enumerate(s_t): if not used[j] and i != j: temp = sum_add(s_term1, s_term2, method) - if isinstance(temp, Sum) or isinstance(temp, Mul): + if isinstance(temp, (Sum, Mul)): s_t[i] = temp s_term1 = s_t[i] used[j] = True diff --git a/sympy/solvers/ode/nonhomogeneous.py b/sympy/solvers/ode/nonhomogeneous.py index 92e0ee60c6ea..55ce1083ac09 100644 --- a/sympy/solvers/ode/nonhomogeneous.py +++ b/sympy/solvers/ode/nonhomogeneous.py @@ -188,7 +188,7 @@ def _get_const_characteristic_eq_sols(r, func, order): chareq, symbol = S.Zero, Dummy('x') for i in r.keys(): - if type(i) == str or i < 0: + if isinstance(i, str) or i < 0: pass else: chareq += r[i]*symbol**i diff --git a/sympy/solvers/solvers.py b/sympy/solvers/solvers.py index 68cb63d6b9a5..2c8fc25455f4 100644 --- a/sympy/solvers/solvers.py +++ b/sympy/solvers/solvers.py @@ -2689,7 +2689,7 @@ def equal(expr1, expr2): g = _filtered_gens(eq.as_poly(), sym) up_or_log = set() for gi in g: - if isinstance(gi, exp) or (gi.is_Pow and gi.base == S.Exp1) or isinstance(gi, log): + if isinstance(gi, (exp, log)) or (gi.is_Pow and gi.base == S.Exp1): up_or_log.add(gi) elif gi.is_Pow: gisimp = powdenest(expand_power_exp(gi)) diff --git a/sympy/stats/rv_interface.py b/sympy/stats/rv_interface.py index b9c8af4a35a1..e58aec48b85e 100644 --- a/sympy/stats/rv_interface.py +++ b/sympy/stats/rv_interface.py @@ -437,7 +437,7 @@ def median(X, evaluate=True, **kwargs): pspace(X).probability(Eq(X, key)) >= Rational(1, 2): result.append(key) return FiniteSet(*result) - if isinstance(pspace(X), ContinuousPSpace) or isinstance(pspace(X), DiscretePSpace): + if isinstance(pspace(X), (ContinuousPSpace, DiscretePSpace)): cdf = pspace(X).compute_cdf(X) x = Dummy('x') result = solveset(piecewise_fold(cdf(x) - Rational(1, 2)), x, pspace(X).set) diff --git a/sympy/stats/stochastic_process_types.py b/sympy/stats/stochastic_process_types.py index e048a752b920..ea81d59fc64a 100644 --- a/sympy/stats/stochastic_process_types.py +++ b/sympy/stats/stochastic_process_types.py @@ -579,16 +579,16 @@ def probability(self, condition, given_condition=None, evaluate=True, **kwargs): s = Rational(0, 1) n = len(self.state_space) - if isinstance(condition, Eq) or isinstance(condition, Ne): + if isinstance(condition, (Eq, Ne)): for i in range(0, n): s += self.probability(Eq(rv[0], i), Eq(rv[1], i)) * self.probability(Eq(rv[1], i), new_given_condition) return s if isinstance(condition, Eq) else 1 - s else: upper = 0 greater = False - if isinstance(condition, Ge) or isinstance(condition, Lt): + if isinstance(condition, (Ge, Lt)): upper = 1 - if isinstance(condition, Gt) or isinstance(condition, Ge): + if isinstance(condition, (Ge, Gt)): greater = True for i in range(0, n): @@ -701,7 +701,7 @@ def _symbolic_probability(self, condition, new_given_condition, rv, min_key_rv): next_state = condition.rhs if isinstance(condition.lhs, RandomIndexedSymbol) \ else condition.lhs - if isinstance(condition, Eq) or isinstance(condition, Ne): + if isinstance(condition, (Eq, Ne)): if isinstance(self, DiscreteMarkovChain): P = self.transition_probabilities**(rv[0].key - min_key_rv.key) else: @@ -711,9 +711,9 @@ def _symbolic_probability(self, condition, new_given_condition, rv, min_key_rv): else: upper = 1 greater = False - if isinstance(condition, Ge) or isinstance(condition, Lt): + if isinstance(condition, (Ge, Lt)): upper = 0 - if isinstance(condition, Gt) or isinstance(condition, Ge): + if isinstance(condition, (Ge, Gt)): greater = True k = Dummy('k') condition = Eq(condition.lhs, k) if isinstance(condition.lhs, RandomIndexedSymbol)\ diff --git a/sympy/vector/implicitregion.py b/sympy/vector/implicitregion.py index 876663d4f5f0..ae02ea7866bb 100644 --- a/sympy/vector/implicitregion.py +++ b/sympy/vector/implicitregion.py @@ -226,7 +226,7 @@ def _regular_point_ellipse(self, a, b, c, d, e, f): flag = True continue - if not (isinstance(sol_z, Integer) or isinstance(sol_z, int)): + if not isinstance(sol_z, (int, Integer)): syms_z = sol_z.free_symbols if len(syms_z) == 1: diff --git a/sympy/vector/parametricregion.py b/sympy/vector/parametricregion.py index 6c00e238d5bc..f5a1f3a13012 100644 --- a/sympy/vector/parametricregion.py +++ b/sympy/vector/parametricregion.py @@ -58,7 +58,7 @@ def __new__(cls, definition, *bounds): bounds = Tuple(*bounds) for bound in bounds: - if isinstance(bound, tuple) or isinstance(bound, Tuple): + if isinstance(bound, (tuple, Tuple)): if len(bound) != 3: raise ValueError("Tuple should be in the form (parameter, lowerbound, upperbound)") parameters += (bound[0],) @@ -66,7 +66,7 @@ def __new__(cls, definition, *bounds): else: parameters += (bound,) - if not (isinstance(definition, tuple) or isinstance(definition, Tuple)): + if not isinstance(definition, (tuple, Tuple)): definition = (definition,) obj = super().__new__(cls, Tuple(*definition), *bounds)