Skip to content

Commit

Permalink
Trac #18476: some cleanup in symbolic/
Browse files Browse the repository at this point in the history
* put raise statements into python3 syntax
* correct some problems found by pyflakes
in the symbolic/ directory

URL: http://trac.sagemath.org/18476
Reported by: chapoton
Ticket author(s): Frédéric Chapoton
Reviewer(s): André Apitzsch
  • Loading branch information
Release Manager authored and vbraun committed May 24, 2015
2 parents e8b4426 + 330a9a8 commit 5f94203
Show file tree
Hide file tree
Showing 12 changed files with 40 additions and 44 deletions.
4 changes: 0 additions & 4 deletions src/sage/symbolic/assumptions.py
Expand Up @@ -155,9 +155,6 @@ def assume(self):
self._context = maxima.newcontext('context' + maxima._next_var_name())
try:
maxima.eval("declare(%s, %s)" % (self._var._maxima_init_(), self._assumption))
# except TypeError, mess:
# if 'inconsistent' in str(mess): # note Maxima doesn't tell you if declarations are redundant
# raise ValueError, "Assumption is inconsistent"
except RuntimeError as mess:
if 'inconsistent' in str(mess): # note Maxima doesn't tell you if declarations are redundant
raise ValueError("Assumption is inconsistent")
Expand Down Expand Up @@ -605,7 +602,6 @@ def _forget_all():
sage: sin(m*pi).simplify()
sin(pi*m)
"""
from sage.calculus.calculus import maxima
global _assumptions
if len(_assumptions) == 0:
return
Expand Down
2 changes: 1 addition & 1 deletion src/sage/symbolic/callable.py
Expand Up @@ -239,7 +239,7 @@ def unify_arguments(self, x):
b = x.arguments()

# Rule #1
if [str(x) for x in a] == [str(x) for x in b]:
if [str(y) for y in a] == [str(z) for z in b]:
return a

# Rule #2
Expand Down
2 changes: 1 addition & 1 deletion src/sage/symbolic/expression.pyx
Expand Up @@ -11259,7 +11259,7 @@ cdef class Expression(CommutativeRingElement):
from sage.symbolic.function_factory import SymbolicFunction

if not self.has(Y):
raise ValueError, "Expression {} contains no {} terms".format(self, Y)
raise ValueError("Expression {} contains no {} terms".format(self, Y))
x = SR.symbol()
yy = SR.symbol()
y = SymbolicFunction('y', 1)(x)
Expand Down
2 changes: 2 additions & 0 deletions src/sage/symbolic/expression_conversions.py
Expand Up @@ -16,6 +16,7 @@
###############################################################################

import operator as _operator
from sage.rings.rational_field import QQ
from sage.symbolic.ring import SR
from sage.symbolic.pynac import I
from sage.functions.all import exp
Expand All @@ -24,6 +25,7 @@
from functools import reduce
GaussianField = I.pyobject().parent()


class FakeExpression(object):
r"""
Pynac represents `x/y` as `xy^{-1}`. Often, tree-walkers would prefer
Expand Down
28 changes: 14 additions & 14 deletions src/sage/symbolic/function.pyx
Expand Up @@ -63,7 +63,7 @@ cdef class Function(SageObject):
TESTS::
# eval_func raises exception
sage: def ef(self, x): raise RuntimeError, "foo"
sage: def ef(self, x): raise RuntimeError("foo")
sage: bar = function("bar", nargs=1, eval_func=ef)
sage: bar(x)
Traceback (most recent call last):
Expand Down Expand Up @@ -96,17 +96,17 @@ cdef class Function(SageObject):
# latex printing can be customised either by setting a string latex_name
# or giving a custom function argument print_latex_func
if latex_name and hasattr(self, '_print_latex_'):
raise ValueError, "only one of latex_name or _print_latex_ should be specified."
raise ValueError("only one of latex_name or _print_latex_ should be specified.")

# only one of derivative and tderivative should be defined
if hasattr(self, '_derivative_') and hasattr(self, '_tderivative_'):
raise ValueError, "only one of _derivative_ or _tderivative_ should be defined."
raise ValueError("only one of _derivative_ or _tderivative_ should be defined.")

for fname in sfunctions_funcs:
real_fname = '_%s_'%fname
if hasattr(self, real_fname) and not \
callable(getattr(self, real_fname)):
raise ValueError, real_fname + " parameter must be callable"
raise ValueError(real_fname + " parameter must be callable")

if not self._is_registered():
self._register_function()
Expand All @@ -124,7 +124,7 @@ cdef class Function(SageObject):
Check if this function is already registered. If it is, set
`self._serial` to the right value.
"""
raise NotImplementedError, "this is an abstract base class, it shouldn't be initialized directly"
raise NotImplementedError("this is an abstract base class, it shouldn't be initialized directly")

cdef _register_function(self):
"""
Expand Down Expand Up @@ -408,15 +408,15 @@ cdef class Function(SageObject):
"""
if self._nargs > 0 and len(args) != self._nargs:
raise TypeError, "Symbolic function %s takes exactly %s arguments (%s given)"%(self._name, self._nargs, len(args))
raise TypeError("Symbolic function %s takes exactly %s arguments (%s given)" % (self._name, self._nargs, len(args)))

# support fast_float
if self._nargs == 1:
if isinstance(args[0], FastDoubleFunc):
try:
method = getattr(args[0], self._name)
except AttributeError, err:
raise TypeError, "cannot handle fast float arguments"
except AttributeError:
raise TypeError("cannot handle fast float arguments")
else:
return method()

Expand Down Expand Up @@ -487,12 +487,12 @@ cdef class Function(SageObject):
try:
nargs[i] = SR.coerce(carg)
except Exception:
raise TypeError, "cannot coerce arguments: %s"%(err)
raise TypeError("cannot coerce arguments: %s" % (err))
args = nargs
else: # coerce == False
for a in args:
if not isinstance(a, Expression):
raise TypeError, "arguments must be symbolic expressions"
raise TypeError("arguments must be symbolic expressions")

cdef GEx res
cdef GExVector vec
Expand Down Expand Up @@ -861,7 +861,7 @@ cdef class GinacFunction(BuiltinFunction):
try:
self._serial = find_function(fname, self._nargs)
except ValueError as err:
raise ValueError, "cannot find GiNaC function with name %s and %s arguments"%(fname, self._nargs)
raise ValueError("cannot find GiNaC function with name %s and %s arguments" % (fname, self._nargs))

global sfunction_serial_dict
return self._serial in sfunction_serial_dict
Expand Down Expand Up @@ -1097,7 +1097,7 @@ cdef class BuiltinFunction(Function):
self.__init__()
else:
# we should never end up here
raise ValueError, "cannot read pickle"
raise ValueError("cannot read pickle")


cdef class SymbolicFunction(Function):
Expand Down Expand Up @@ -1307,7 +1307,7 @@ cdef class SymbolicFunction(Function):
# check input
if not ((state[0] == 1 and len(state) == 6) or \
(state[0] == 2 and len(state) == 7)):
raise ValueError, "unknown state information"
raise ValueError("unknown state information")

name = state[1]
nargs = state[2]
Expand Down Expand Up @@ -1366,7 +1366,7 @@ cdef class DeprecatedSFunction(SymbolicFunction):
try:
return self.__dict__[attr]
except KeyError:
raise AttributeError, attr
raise AttributeError(attr)

def __setattr__(self, attr, value):
"""
Expand Down
2 changes: 1 addition & 1 deletion src/sage/symbolic/function_factory.py
Expand Up @@ -323,7 +323,7 @@ def function(s, *args, **kwds):
names = s.split(' ')
else:
names = [s]
names = [s.strip() for s in names if s.strip()]
names = [sn.strip() for sn in names if sn.strip()]

funcs = [function_factory(name, **kwds) for name in names]

Expand Down
6 changes: 3 additions & 3 deletions src/sage/symbolic/getitem.pyx
Expand Up @@ -128,7 +128,7 @@ cdef class OperandsWrapper(SageObject):
if arg.step:
step = arg.step
if step != arg.step:
raise ValueError, "step value must be an integer"
raise ValueError("step value must be an integer")
else:
step = 1
return [new_Expression_from_GEx(self._expr._parent,
Expand All @@ -139,12 +139,12 @@ cdef class OperandsWrapper(SageObject):
if isinstance(arg, (list, tuple)):
# handle nested index
if len(arg) == 0: # or not all(lambda x: x in ZZ for t in args):
raise TypeError, ind_err_msg
raise TypeError(ind_err_msg)
GEx_construct_ex(&cur_ex, self._expr._gobj)
for x in arg:
nops = cur_ex.nops()
if nops == 0:
raise TypeError, "expressions containing only a numeric coefficient, constant or symbol have no operands"
raise TypeError("expressions containing only a numeric coefficient, constant or symbol have no operands")
ind = normalize_index(x, nops, ind_err_msg)
cur_ex = cur_ex.op(ind)
return new_Expression_from_GEx(self._expr._parent, cur_ex)
Expand Down
8 changes: 4 additions & 4 deletions src/sage/symbolic/pynac.pyx
Expand Up @@ -179,11 +179,11 @@ cdef public GEx pyExpression_to_ex(object res) except *:
functions back to C++ level.
"""
if res is None:
raise TypeError, "function returned None, expected return value of type sage.symbolic.expression.Expression"
raise TypeError("function returned None, expected return value of type sage.symbolic.expression.Expression")
try:
t = ring.SR.coerce(res)
except TypeError as err:
raise TypeError, "function did not return a symbolic expression or an element that can be coerced into a symbolic expression"
raise TypeError("function did not return a symbolic expression or an element that can be coerced into a symbolic expression")
return (<Expression>t)._gobj

cdef public object paramset_to_PyTuple(const_paramset_ref s):
Expand Down Expand Up @@ -1336,7 +1336,7 @@ def py_factorial_py(x):
cdef public object py_doublefactorial(object x) except +:
n = Integer(x)
if n < -1:
raise ValueError, "argument must be >= -1"
raise ValueError("argument must be >= -1")
from sage.misc.misc_c import prod # fast balanced product
return prod([n - 2*i for i in range(n//2)])

Expand Down Expand Up @@ -1656,7 +1656,7 @@ cdef public object py_atan2(object x, object y) except +:
if sgn_x > 0:
return 0
elif x == 0:
raise ValueError, "arctan2(0,0) undefined"
raise ValueError("arctan2(0,0) undefined")
else:
return pi_n

Expand Down
3 changes: 2 additions & 1 deletion src/sage/symbolic/random_tests.py
Expand Up @@ -17,7 +17,8 @@
from sage.rings.all import QQ
from sage.symbolic.ring import SR
import sage.symbolic.pynac
from sage.symbolic.constants import *
from sage.symbolic.constants import (pi, e, golden_ratio, log2, euler_gamma,
catalan, khinchin, twinprime, mertens)
from sage.functions.hypergeometric import hypergeometric


Expand Down
16 changes: 8 additions & 8 deletions src/sage/symbolic/relation.py
Expand Up @@ -329,7 +329,7 @@
"""
import operator
from sage.calculus.calculus import maxima


def test_relation_maxima(relation):
"""
Expand Down Expand Up @@ -459,20 +459,20 @@ def test_relation_maxima(relation):
if relation.operator() == operator.eq: # operator is equality
try:
s = m.parent()._eval_line('is (equal(%s,%s))'%(repr(m.lhs()),repr(m.rhs())))
except TypeError as msg:
raise ValueError("unable to evaluate the predicate '%s'"%repr(relation))
except TypeError:
raise ValueError("unable to evaluate the predicate '%s'" % repr(relation))

elif relation.operator() == operator.ne: # operator is not equal
try:
s = m.parent()._eval_line('is (notequal(%s,%s))'%(repr(m.lhs()),repr(m.rhs())))
except TypeError as msg:
raise ValueError("unable to evaluate the predicate '%s'"%repr(relation))
except TypeError:
raise ValueError("unable to evaluate the predicate '%s'" % repr(relation))

else: # operator is < or > or <= or >=, which Maxima handles fine
try:
s = m.parent()._eval_line('is (%s)'%repr(m))
except TypeError as msg:
raise ValueError("unable to evaluate the predicate '%s'"%repr(relation))
except TypeError:
raise ValueError("unable to evaluate the predicate '%s'" % repr(relation))

if s == 'true':
return True
Expand Down Expand Up @@ -1153,7 +1153,7 @@ def solve_ineq_univar(ineq):
"""
ineqvar = ineq.variables()
if len(ineqvar) != 1:
raise NotImplementedError, "The command solve_ineq_univar accepts univariate inequalities only. Your variables are ", ineqvar
raise NotImplementedError("The command solve_ineq_univar accepts univariate inequalities only. Your variables are " + ineqvar)
ineq0 = ineq._maxima_()
ineq0.parent().eval("if solve_rat_ineq_loaded#true then (solve_rat_ineq_loaded:true,load(\"solve_rat_ineq.mac\")) ")
sol = ineq0.solve_rat_ineq().sage()
Expand Down
10 changes: 4 additions & 6 deletions src/sage/symbolic/ring.pyx
Expand Up @@ -268,7 +268,7 @@ cdef class SymbolicRing(CommutativeRing):
return self(symbolic_expression_from_string(x))
except SyntaxError as err:
msg, s, pos = err.args
raise TypeError, "%s: %s !!! %s" % (msg, s[:pos], s[pos:])
raise TypeError("%s: %s !!! %s" % (msg, s[:pos], s[pos:]))

from sage.rings.infinity import (infinity, minus_infinity,
unsigned_infinity)
Expand Down Expand Up @@ -674,7 +674,7 @@ cdef class SymbolicRing(CommutativeRing):
return self.symbol(name, latex_name=formatted_latex_name, domain=domain)
if len(names_list) > 1:
if latex_name:
raise ValueError, "cannot specify latex_name for multiple symbol names"
raise ValueError("cannot specify latex_name for multiple symbol names")
return tuple([self.symbol(s, domain=domain) for s in names_list])

def _repr_element_(self, Expression x):
Expand Down Expand Up @@ -783,7 +783,7 @@ cdef class SymbolicRing(CommutativeRing):
try:
d[ vars[i] ] = arg
except IndexError:
raise ValueError, "the number of arguments must be less than or equal to %s"%len(vars)
raise ValueError("the number of arguments must be less than or equal to %s"%len(vars))

return _the_element.subs(d, **kwds)

Expand Down Expand Up @@ -1046,6 +1046,4 @@ def isidentifier(x):
code = parser.expr(x).compile()
except (MemoryError, OverflowError, SyntaxError, SystemError, parser.ParserError), msg:
return False
return len(code.co_names)==1 and code.co_names[0]==x


return len(code.co_names) == 1 and code.co_names[0] == x
1 change: 0 additions & 1 deletion src/sage/symbolic/tests.py
Expand Up @@ -39,4 +39,3 @@ def rational_powers_memleak():
c1 = sum(1 for obj in gc.get_objects())
# Test that we do not leak an object at each iteration
return (c1 - c0) >= 1000

0 comments on commit 5f94203

Please sign in to comment.