Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

beautify SymPyDeprecationWarning; use warn() method.

  • Loading branch information...
commit 1001408d9642b16a094c24afcf4652d5a96d2194 1 parent 935df6d
@smichr smichr authored
View
6 sympy/core/decorators.py
@@ -7,7 +7,6 @@
from functools import wraps
from sympify import SympifyError, sympify
-import warnings
def deprecated(func):
"""This is a decorator which can be used to mark functions
@@ -16,7 +15,10 @@ def deprecated(func):
@wraps(func)
def new_func(*args, **kwargs):
from sympy.utilities.exceptions import SymPyDeprecationWarning
- warnings.warn(SymPyDeprecationWarning("Call to deprecated function.", feature=func.__name__ + "()"))
+ SymPyDeprecationWarning(
+ "Call to deprecated function.",
+ feature=func.__name__ + "()"
+ ).warn()
return func(*args, **kwargs)
return new_func
View
10 sympy/core/expr.py
@@ -1490,20 +1490,18 @@ def as_coeff_terms(self, *deps):
"""
This method is deprecated. Use .as_coeff_mul() instead.
"""
- import warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
- warnings.warn(SymPyDeprecationWarning(feature="as_coeff_terms()",
- useinstead="as_coeff_mul()"))
+ SymPyDeprecationWarning(feature="as_coeff_terms()",
+ useinstead="as_coeff_mul()").warn()
return self.as_coeff_mul(*deps)
def as_coeff_factors(self, *deps):
"""
This method is deprecated. Use .as_coeff_add() instead.
"""
- import warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
- warnings.warn(SymPyDeprecationWarning(feature="as_coeff_factors()",
- useinstead="as_coeff_add()"))
+ SymPyDeprecationWarning(feature="as_coeff_factors()",
+ useinstead="as_coeff_add()").warn()
return self.as_coeff_add(*deps)
def as_coeff_mul(self, *deps):
View
17 sympy/core/symbol.py
@@ -10,7 +10,6 @@
from sympy.utilities.exceptions import SymPyDeprecationWarning
import re
-import warnings
class Symbol(AtomicExpr, Boolean):
"""
@@ -60,10 +59,10 @@ def __new__(cls, name, **assumptions):
"""
if 'dummy' in assumptions:
- warnings.warn(
- SymPyDeprecationWarning(
- feature="Symbol('x', dummy=True)",
- useinstead="Dummy() or symbols(..., cls=Dummy)"))
+ SymPyDeprecationWarning(
+ feature="Symbol('x', dummy=True)",
+ useinstead="Dummy() or symbols(..., cls=Dummy)"
+ ).warn()
if assumptions.pop('dummy'):
return Dummy(name, **assumptions)
if assumptions.get('zero', False):
@@ -286,10 +285,10 @@ def symbols(names, **args):
"""
result = []
if 'each_char' in args:
- warnings.warn(
- SymPyDeprecationWarning(
- feature="each_char in the options to symbols() and var()",
- useinstead="spaces or commas between symbol names"))
+ SymPyDeprecationWarning(
+ feature="each_char in the options to symbols() and var()",
+ useinstead="spaces or commas between symbol names"
+ ).warn()
if isinstance(names, basestring):
names = names.strip()
View
10 sympy/core/tests/test_symbol.py
@@ -203,13 +203,11 @@ def test_symbols_each_char():
z = Symbol('z')
# First, test the warning
- warnings.filterwarnings("error", "The each_char option to symbols\(\) and var\(\) is "
- "deprecated. Separate symbol names by spaces or commas instead.")
- raises(SymPyDeprecationWarning, "symbols('xyz', each_char=True)")
- raises(SymPyDeprecationWarning, "symbols('xyz', each_char=False)")
+ warnings.filterwarnings("error")
+ raises(UserWarning, "symbols('xyz', each_char=True)")
+ raises(UserWarning, "symbols('xyz', each_char=False)")
# now test the actual output
- warnings.filterwarnings("ignore", "The each_char option to symbols\(\) and var\(\) is "
- "deprecated. Separate symbol names by spaces or commas instead.")
+ warnings.filterwarnings("ignore")
assert symbols(['wx', 'yz'], each_char=True) == [(w, x), (y, z)]
assert all(w.is_Function for w in flatten(symbols(['wx', 'yz'], each_char=True, cls=Function)))
assert symbols('xyz', each_char=True) == (x, y, z)
View
37 sympy/matrices/matrices.py
@@ -21,7 +21,6 @@
from sympy.core.decorators import call_highest_priority
import random
-import warnings
from types import FunctionType
class MatrixError(Exception):
@@ -1912,7 +1911,9 @@ def zeros(cls, r, c=None):
fill
"""
if is_sequence(r):
- warnings.warn(SymPyDeprecationWarning("Pass row and column count as zeros(%i, %i)." % r))
+ SymPyDeprecationWarning(
+ "Pass row and column count as zeros(%i, %i)." % r
+ ).warn()
r, c = r
else:
c = r if c is None else c
@@ -2476,11 +2477,11 @@ def rref(self, simplified=False, iszerofunc=_iszero,
[0, 1], [0, 1])
"""
if simplified is not False:
- warnings.warn(filldedent('''
- Use of simplified is deprecated. Set simplify=True to
- use SymPy's simplify function or set simplify to your
- own custom simplification function.
- '''))
+ SymPyDeprecationWarning(
+ feature="'simplified' as a keyword to rref",
+ useinstead="simplify=True or set simplify equal to your " +
+ "own custom simplification function"
+ ).warn()
simplify = simplify or True
simpfunc = simplify if isinstance(simplify, FunctionType) else _simplify
pivot, r = 0, self[:,:].as_mutable() # pivot: index of next row to contain a pivot
@@ -2515,11 +2516,11 @@ def nullspace(self, simplified=False, simplify=False):
Returns list of vectors (Matrix objects) that span nullspace of self
"""
if simplified is not False:
- warnings.warn(filldedent('''
- Use of simplified is deprecated. Set simplify=True to
- use SymPy's simplify function or set simplify to your
- own custom simplification function.
- '''))
+ SymPyDeprecationWarning(
+ feature="'simplified' as a keyword to rref",
+ useinstead="simplify=True or set simplify equal to your " +
+ "own custom simplification function"
+ ).warn()
simplify = simplify or True
simpfunc = simplify if isinstance(simplify, FunctionType) else _simplify
reduced, pivots = self.rref(simplify=simpfunc)
@@ -3829,7 +3830,9 @@ def zeros(r, c=None, cls=MutableMatrix):
diag
"""
if is_sequence(r):
- warnings.warn(SymPyDeprecationWarning("Pass row and column count as zeros(%i, %i)." % r))
+ SymPyDeprecationWarning(
+ "Pass row and column count as zeros(%i, %i)." % r
+ ).warn()
r, c = r
else:
c = r if c is None else c
@@ -3849,7 +3852,9 @@ def ones(r, c=None):
"""
if is_sequence(r):
- warnings.warn(SymPyDeprecationWarning("Pass row and column count as ones(%i, %i)." % r))
+ SymPyDeprecationWarning(
+ "Pass row and column count as ones(%i, %i)." % r
+ ).warn()
r, c = r
else:
c = r if c is None else c
@@ -4549,7 +4554,9 @@ def zeros(cls, r, c=None):
"""Returns a matrix of zeros with ``r`` rows and ``c`` columns;
if ``c`` is omitted a square matrix will be returned."""
if is_sequence(r):
- warnings.warn("Pass row and column count as zeros(%i, %i)." % r, SymPyDeprecationWarning)
+ SymPyDeprecationWarning(
+ "Pass row and column count as zeros(%i, %i)." % r
+ ).warn()
r, c = r
else:
c = r if c is None else c
View
9 sympy/solvers/ode.py
@@ -1132,14 +1132,17 @@ def checkodesol(ode, sol, func=None, order='auto', solve_for_func=True):
# ----------
# assume, during deprecation that sol and func are reversed
if hasattr(sol, '_is_Function') and isinstance(sol, AppliedUndef) and len(sol.args) == 1:
- import warnings
msg = "sol appears to be a valid function. " +\
"The order of sol and func will be reversed. " +\
"If this is not desired, send sol as Eq(sol, 0)."
- warnings.warn(SymPyDeprecationWarning(msg))
+ SymPyDeprecationWarning(msg
+ ).warn()
sol, func = func, sol
elif not (isinstance(func, AppliedUndef) and len(func.args) == 1):
- raise ValueError("func (or sol, during deprecation) must be a function of one variable. Got sol = %s, func = %s" % (sol, func))
+ from sympy.utilities.misc import filldedent
+ raise ValueError(filldedent('''
+ func (or sol, during deprecation) must be a function
+ of one variable. Got sol = %s, func = %s''' % (sol, func)))
# ========== end of deprecation handling
if is_sequence(sol, set):
return type(sol)(map(lambda i: checkodesol(ode, i, order=order,
View
6 sympy/solvers/solvers.py
@@ -46,7 +46,6 @@
from sympy.assumptions import Q, ask
-from warnings import warn
from types import GeneratorType
from collections import defaultdict
@@ -1742,7 +1741,10 @@ def _generate_patterns():
def tsolve(eq, sym):
- warn(SymPyDeprecationWarning(feature="tsolve()", useinstead="solve()"))
+ SymPyDeprecationWarning(
+ feature="tsolve()",
+ useinstead="solve()"
+ ).warn()
return _tsolve(eq, sym)
View
64 sympy/utilities/exceptions.py
@@ -2,6 +2,9 @@
General SymPy exceptions and warnings.
"""
+from sympy.utilities.misc import filldedent
+from warnings import warn as warning
+
class SymPyDeprecationWarning(DeprecationWarning):
r"""A warning for deprecated features of SymPy.
@@ -14,49 +17,54 @@ class SymPyDeprecationWarning(DeprecationWarning):
>>> warnings.warn("Don't do this, it's deprecated", SymPyDeprecationWarning) #doctest:+SKIP
__main__:1: SymPyDeprecationWarning: "Don't do this, it's deprecated"
- The recommended way to use this class is, however, by directly passing
- instances of it to warnings.warn:
+ The recommended way to use this class is, however, is by calling
+ the warn method after constructing the message:
- >>> warnings.warn(SymPyDeprecationWarning("Don't do this, it's deprecated")) #doctest:+SKIP
- __main__:1: SymPyDeprecationWarning: "Don't do this, it's deprecated"
+ >>> SymPyDeprecationWarning("Don't do this, it's deprecated.").warn #doctest:+SKIP
+ __main__:1: SymPyDeprecationWarning:
+
+ Don't do this, it's deprecated.
+
+ warning (see_above, SymPyDeprecationWarning)
To provide additional information, create an instance of this
class in this way:
- >>> SymPyDeprecationWarning(feature="such and such",
+ >>> SymPyDeprecationWarning(
+ ... feature="such and such",
... last_supported_version="1.2.3",
... useinstead="this other feature")
- SymPyDeprecationWarning("The feature such and such is deprecated.
- It will be last supported in SymPy version 1.2.3. Use this other
- feature instead.")
+ The feature such and such is deprecated. It will be last supported in
+ SymPy version 1.2.3. Use this other feature instead.
Either (or both) of the arguments last_supported_version and
- useinstead can be omitted. In this case the corresponding
+ useinstead can be omitted. In this case the corresponding
sentence will not be shown:
>>> SymPyDeprecationWarning(feature="such and such",
... useinstead="this other feature")
- SymPyDeprecationWarning("The feature such and such is deprecated.
- Use this other feature instead.")
+ The feature such and such is deprecated. Use this other feature
+ instead.
You can still provide the argument value. If it is a string, it
will be appended to the end of the message:
- >>> SymPyDeprecationWarning(feature="such and such",
+ >>> SymPyDeprecationWarning(
+ ... feature="such and such",
... useinstead="this other feature",
... value="Contact the developers for further information.")
- SymPyDeprecationWarning("The feature such and such is deprecated.
- Use this other feature instead. Contact the developers for
- further information.")
+ The feature such and such is deprecated. Use this other feature
+ instead. Contact the developers for further information.
If, however, the argument value does not hold a string, a string
representation of the object will be appended to the message:
- >>> SymPyDeprecationWarning(feature="such and such",
+ >>> SymPyDeprecationWarning(
+ ... feature="such and such",
... useinstead="this other feature",
... value=[1,2,3])
- SymPyDeprecationWarning("The feature such and such is deprecated.
- Use this other feature instead. ([1, 2, 3])")
+ The feature such and such is deprecated. Use this other feature
+ instead. ([1, 2, 3])
To mark a function as deprecated, you can use the decorator
@deprecated.
@@ -68,27 +76,29 @@ class in this way:
def __init__(self, value=None, feature=None, last_supported_version=None,
useinstead=None):
- self.fullMessage=""
+ self.fullMessage = ""
if feature:
self.fullMessage = "The feature %s is deprecated." % feature
if last_supported_version:
- self.fullMessage += " It will be last supported in SymPy version %s." % last_supported_version
+ self.fullMessage += " It will be last supported in SymPy version %s." % last_supported_version
if useinstead:
- self.fullMessage += " Use %s instead." % useinstead
+ self.fullMessage += " Use %s instead." % useinstead
if value:
if not isinstance(value, str):
value = "(%s)" % repr(value)
+ value = " " + value
else:
value = ""
- if self.fullMessage:
- if value:
- self.fullMessage += " " + value
- else:
- self.fullMessage = value
+ self.fullMessage += value
def __str__(self):
- return "SymPyDeprecationWarning(\"%s\")" % self.fullMessage
+ return '\n%s\n' % filldedent(self.fullMessage)
+
+ def warn(self):
+ see_above = self
+ # the next line is what the user will see after the error is printed
+ warning (see_above, SymPyDeprecationWarning)
View
9 sympy/utilities/iterables.py
@@ -429,11 +429,10 @@ def numbered_symbols(prefix='x', cls=None, start=0, *args, **assumptions):
"""
if cls is None:
if 'dummy' in assumptions and assumptions.pop('dummy'):
- import warnings
- warnings.warn(
- SymPyDeprecationWarning(
- feature="'dummy' in assumptions",
- useinstead="cls=Dummy to create dummy symbols"))
+ SymPyDeprecationWarning(
+ feature="'dummy' in assumptions",
+ useinstead="cls=Dummy to create dummy symbols"
+ ).warn()
cls = C.Dummy
else:
cls = C.Symbol
View
2  sympy/utilities/tests/test_pickling.py
@@ -35,7 +35,7 @@ def check(a, check_attr=True):
"""
# The below hasattr() check will warn about is_Real in Python 2.5, so
# disable this to keep the tests clean
- warnings.filterwarnings("ignore", ".*is_Real.*", SymPyDeprecationWarning)
+ warnings.filterwarnings("ignore", ".*is_Real.*")
protocols = [0, 1, 2, copy.copy, copy.deepcopy]
# Python 2.x doesn't support the third pickling protocol
if sys.version_info[0] > 2:
Please sign in to comment.
Something went wrong with that request. Please try again.