Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d3d9fad

Browse files
committed
Prefer warn_deprecated instead of warnings.warn.
warn_deprecated has the advantage of always listing the deprecation version and removal version. Hopefully, in the future it will also be able to set the stacklevel more systematically. Redesign the way deprecation of rcParams is done to make it use warn_deprecated. Merge obsolete_set into deprecated_ignore_map as they are semantically similar, it's just that there's no alternative rcParam for obsolete_set. Rename deprecated_set to deprecated_remain_as_none as the former name really doesn't say anything about the deprecation semantics. text.dvipnghack and axes.hold should be completely removed but that'll be another PR.
1 parent 1e6790f commit d3d9fad

File tree

7 files changed

+96
-81
lines changed

7 files changed

+96
-81
lines changed

doc/api/next_api_changes/2018-02-15-AL-deprecations.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ The following modules are deprecated:
1010

1111
The following classes, methods, functions, and attributes are deprecated:
1212

13+
- ``RcParams.msg_depr``, ``RcParams.msg_depr_ignore``,
14+
``RcParams.msg_depr_set``, ``RcParams.msg_obsolete``,
15+
``RcParams.msg_backend_obsolete``,
1316
- ``afm.parse_afm``,
1417
- ``backend_pgf.get_texcommand``,
1518
- ``backend_ps.get_bbox``,

lib/matplotlib/__init__.py

Lines changed: 80 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -123,11 +123,11 @@
123123
import importlib
124124
import inspect
125125
from inspect import Parameter
126-
import itertools
127126
import locale
128127
import logging
129128
import os
130129
from pathlib import Path
130+
import pprint
131131
import re
132132
import shutil
133133
import stat
@@ -800,23 +800,29 @@ def gen_candidates():
800800
return fname
801801

802802

803-
# names of keys to deprecate
804-
# the values are a tuple of (new_name, f_old_2_new, f_new_2_old)
805-
# the inverse function may be `None`
803+
# rcParams deprecated and automatically mapped to another key.
804+
# Values are tuples of (version, new_name, f_old2new, f_new2old).
806805
_deprecated_map = {}
807806

808-
_deprecated_ignore_map = {'nbagg.transparent': 'figure.facecolor'}
807+
# rcParams deprecated; some can manually be mapped to another key.
808+
# Values are tuples of (version, new_name_or_None).
809+
_deprecated_ignore_map = {
810+
'text.dvipnghack': ('2.1', None),
811+
'nbagg.transparent': ('2.2', 'figure.facecolor'),
812+
'plugins.directory': ('2.2', None),
813+
'pgf.debug': ('3.0', None),
814+
}
809815

810-
_obsolete_set = {'pgf.debug', 'plugins.directory', 'text.dvipnghack'}
816+
# rcParams deprecated; can use None to suppress warnings; remain actually
817+
# listed in the rcParams (not included in _all_deprecated).
818+
# Values are typles of (version,)
819+
_deprecated_remain_as_none = {
820+
'axes.hold': ('2.1',),
821+
'backend.qt4': ('2.2',),
822+
'backend.qt5': ('2.2',),
823+
}
811824

812-
# The following may use a value of None to suppress the warning.
813-
# do NOT include in _all_deprecated
814-
_deprecated_set = {'axes.hold',
815-
'backend.qt4',
816-
'backend.qt5'}
817-
818-
_all_deprecated = set(itertools.chain(
819-
_deprecated_ignore_map, _deprecated_map, _obsolete_set))
825+
_all_deprecated = {*_deprecated_map, *_deprecated_ignore_map}
820826

821827

822828
class RcParams(MutableMapping, dict):
@@ -831,16 +837,35 @@ class RcParams(MutableMapping, dict):
831837
validate = {key: converter
832838
for key, (default, converter) in defaultParams.items()
833839
if key not in _all_deprecated}
834-
msg_depr = "%s is deprecated and replaced with %s; please use the latter."
835-
msg_depr_set = ("%s is deprecated. Please remove it from your "
836-
"matplotlibrc and/or style files.")
837-
msg_depr_ignore = "%s is deprecated and ignored. Use %s instead."
838-
msg_obsolete = ("%s is obsolete. Please remove it from your matplotlibrc "
839-
"and/or style files.")
840-
msg_backend_obsolete = ("The {} rcParam was deprecated in version 2.2. In"
841-
" order to force the use of a specific Qt binding,"
842-
" either import that binding first, or set the "
843-
"QT_API environment variable.")
840+
841+
@property
842+
@cbook.deprecated("3.0")
843+
def msg_depr(self):
844+
return "%s is deprecated and replaced with %s; please use the latter."
845+
846+
@property
847+
@cbook.deprecated("3.0")
848+
def msg_depr_ignore(self):
849+
return "%s is deprecated and ignored. Use %s instead."
850+
851+
@property
852+
@cbook.deprecated("3.0")
853+
def msg_depr_set(self):
854+
return ("%s is deprecated. Please remove it from your matplotlibrc "
855+
"and/or style files.")
856+
857+
@property
858+
@cbook.deprecated("3.0")
859+
def msg_obsolete(self):
860+
return ("%s is obsolete. Please remove it from your matplotlibrc "
861+
"and/or style files.")
862+
863+
@property
864+
@cbook.deprecated("3.0")
865+
def msg_backend_obsolete(self):
866+
return ("The {} rcParam was deprecated in version 2.2. In order to "
867+
"force the use of a specific Qt binding, either import that "
868+
"binding first, or set the QT_API environment variable.")
844869

845870
# validate values on the way in
846871
def __init__(self, *args, **kwargs):
@@ -849,26 +874,25 @@ def __init__(self, *args, **kwargs):
849874
def __setitem__(self, key, val):
850875
try:
851876
if key in _deprecated_map:
852-
alt_key, alt_val, inverse_alt = _deprecated_map[key]
853-
warnings.warn(self.msg_depr % (key, alt_key),
854-
mplDeprecation)
877+
version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
878+
cbook.warn_deprecated(
879+
version, key, obj_type="rcparam", alternative=alt_key)
855880
key = alt_key
856881
val = alt_val(val)
857-
elif key in _deprecated_set and val is not None:
882+
elif key in _deprecated_remain_as_none and val is not None:
883+
version, = _deprecated_remain_as_none[key]
884+
addendum = None
858885
if key.startswith('backend'):
859-
warnings.warn(self.msg_backend_obsolete.format(key),
860-
mplDeprecation)
861-
else:
862-
warnings.warn(self.msg_depr_set % key,
863-
mplDeprecation)
886+
addendum = (
887+
"In order to force the use of a specific Qt binding, "
888+
"either import that binding first, or set the QT_API "
889+
"environment variable.")
890+
cbook.warn_deprecated(
891+
"2.2", key, obj_type="rcparam", addendum=addendum)
864892
elif key in _deprecated_ignore_map:
865-
alt = _deprecated_ignore_map[key]
866-
warnings.warn(self.msg_depr_ignore % (key, alt),
867-
mplDeprecation)
868-
return
869-
elif key in _obsolete_set:
870-
warnings.warn(self.msg_obsolete % (key, ),
871-
mplDeprecation)
893+
version, alt_key = _deprecated_ignore_map[key]
894+
cbook.warn_deprecated(
895+
version, key, obj_type="rcparam", alternative=alt_key)
872896
return
873897
try:
874898
cval = self.validate[key](val)
@@ -881,42 +905,30 @@ def __setitem__(self, key, val):
881905
'list of valid parameters.' % (key,))
882906

883907
def __getitem__(self, key):
884-
inverse_alt = None
885908
if key in _deprecated_map:
886-
alt_key, alt_val, inverse_alt = _deprecated_map[key]
887-
warnings.warn(self.msg_depr % (key, alt_key),
888-
mplDeprecation)
889-
key = alt_key
909+
version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
910+
cbook.warn_deprecated(
911+
version, key, obj_type="rcparam", alternative=alt_key)
912+
return inverse_alt(dict.__getitem__(self, alt_key))
890913

891914
elif key in _deprecated_ignore_map:
892-
alt = _deprecated_ignore_map[key]
893-
warnings.warn(self.msg_depr_ignore % (key, alt),
894-
mplDeprecation)
895-
key = alt
896-
897-
elif key in _obsolete_set:
898-
warnings.warn(self.msg_obsolete % (key, ),
899-
mplDeprecation)
900-
return None
901-
902-
val = dict.__getitem__(self, key)
903-
if inverse_alt is not None:
904-
return inverse_alt(val)
905-
else:
906-
return val
915+
version, alt_key = _deprecated_ignore_map[key]
916+
cbook.warn_deprecated(
917+
version, key, obj_type, alternative=alt_key)
918+
return dict.__getitem__(self, alt_key) if alt_key else None
919+
920+
return dict.__getitem__(self, key)
907921

908922
def __repr__(self):
909-
import pprint
910923
class_name = self.__class__.__name__
911924
indent = len(class_name) + 1
912925
repr_split = pprint.pformat(dict(self), indent=1,
913926
width=80 - indent).split('\n')
914927
repr_indented = ('\n' + ' ' * indent).join(repr_split)
915-
return '{0}({1})'.format(class_name, repr_indented)
928+
return '{}({})'.format(class_name, repr_indented)
916929

917930
def __str__(self):
918-
return '\n'.join('{0}: {1}'.format(k, v)
919-
for k, v in sorted(self.items()))
931+
return '\n'.join(map('{0[0]}: {0[1]}'.format, sorted(self.items())))
920932

921933
def __iter__(self):
922934
"""Yield sorted list of keys."""
@@ -1043,10 +1055,10 @@ def _rc_params_in_file(fname, fail_on_error=False):
10431055
warnings.warn('Bad val "%s" on %s\n\t%s' %
10441056
(val, error_details, msg))
10451057
elif key in _deprecated_ignore_map:
1046-
warnings.warn('%s is deprecated. Update your matplotlibrc to use '
1047-
'%s instead.' % (key, _deprecated_ignore_map[key]),
1048-
mplDeprecation)
1049-
1058+
version, alt_key = _deprecated_ignore_map[key]
1059+
cbook.warn_deprecated(
1060+
version, key, alternative=alt_key,
1061+
addendum="Please update your matplotlibrc.")
10501062
else:
10511063
print("""
10521064
Bad key "%s" on line %d in

lib/matplotlib/axes/_base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1334,8 +1334,8 @@ def set_adjustable(self, adjustable, share=False):
13341334
and independently on each Axes as it is drawn.
13351335
"""
13361336
if adjustable == 'box-forced':
1337-
warnings.warn("The 'box-forced' keyword argument is deprecated"
1338-
" since 2.2.", cbook.mplDeprecation)
1337+
cbook.warn_deprecated(
1338+
"2.2", "box-forced", obj_type="keyword argument")
13391339
if adjustable not in ('box', 'datalim', 'box-forced'):
13401340
raise ValueError("argument must be 'box', or 'datalim'")
13411341
if share:

lib/matplotlib/axes/_subplots.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
from matplotlib import docstring
55
import matplotlib.artist as martist
66
from matplotlib.axes._axes import Axes
7-
from matplotlib.cbook import mplDeprecation
87
from matplotlib.gridspec import GridSpec, SubplotSpec
98
import matplotlib._layoutbox as layoutbox
109

lib/matplotlib/cbook/deprecation.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,8 @@ def _generate_deprecation_message(
4040
if removal else
4141
"")))
4242
+ "."
43-
+ (" Use {alternative} instead." if alternative else ""))
43+
+ (" Use {alternative} instead." if alternative else "")
44+
+ (" {addendum}" if addendum else ""))
4445

4546
return message.format(func=name, name=name, obj_type=obj_type, since=since,
4647
removal=removal, alternative=alternative)
@@ -99,7 +100,8 @@ def warn_deprecated(
99100
100101
"""
101102
message = _generate_deprecation_message(
102-
since, message, name, alternative, pending, obj_type, removal=removal)
103+
since, message, name, alternative, pending, obj_type, addendum,
104+
removal=removal)
103105
warnings.warn(message, mplDeprecation, stacklevel=2)
104106

105107

lib/matplotlib/gridspec.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
from matplotlib import _pylab_helpers, tight_layout, rcParams
2424
from matplotlib.transforms import Bbox
2525
import matplotlib._layoutbox as layoutbox
26-
from matplotlib.cbook import mplDeprecation
2726

2827
_log = logging.getLogger(__name__)
2928

@@ -265,8 +264,8 @@ def get_subplot_params(self, figure=None, fig=None):
265264
parameters are from rcParams unless a figure attribute is set.
266265
"""
267266
if fig is not None:
268-
warnings.warn("the 'fig' kwarg is deprecated "
269-
"use 'figure' instead", mplDeprecation)
267+
cbook.warn_deprecated("2.2", "fig", obj_type="keyword argument",
268+
alternative="figure")
270269
if figure is None:
271270
figure = fig
272271

@@ -355,8 +354,8 @@ def get_subplot_params(self, figure=None, fig=None):
355354
"""Return a dictionary of subplot layout parameters.
356355
"""
357356
if fig is not None:
358-
warnings.warn("the 'fig' kwarg is deprecated "
359-
"use 'figure' instead", mplDeprecation)
357+
cbook.warn_deprecated("2.2", "fig", obj_type="keyword argument",
358+
alternative="figure")
360359
if figure is None:
361360
figure = fig
362361

lib/matplotlib/tests/test_rcparams.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -458,7 +458,7 @@ def test_rcparams_reset_after_fail():
458458

459459
def test_if_rctemplate_is_up_to_date():
460460
# This tests if the matplotlibrc.template file contains all valid rcParams.
461-
deprecated = {*mpl._all_deprecated, *mpl._deprecated_set}
461+
deprecated = {*mpl._all_deprecated, *mpl._deprecated_remain_as_none}
462462
path_to_rc = os.path.join(mpl.get_data_path(), 'matplotlibrc')
463463
with open(path_to_rc, "r") as f:
464464
rclines = f.readlines()
@@ -477,8 +477,8 @@ def test_if_rctemplate_is_up_to_date():
477477
if not found:
478478
missing.update({k: v})
479479
if missing:
480-
raise ValueError("The following params are missing " +
481-
"in the matplotlibrc.template file: {}"
480+
raise ValueError("The following params are missing in the "
481+
"matplotlibrc.template file: {}"
482482
.format(missing.items()))
483483

484484

0 commit comments

Comments
 (0)