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

Skip to content

Commit b100c00

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 ead2ff8 commit b100c00

File tree

7 files changed

+97
-83
lines changed

7 files changed

+97
-83
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
@@ -1310,8 +1310,8 @@ def set_adjustable(self, adjustable, share=False):
13101310
and independently on each Axes as it is drawn.
13111311
"""
13121312
if adjustable == 'box-forced':
1313-
warnings.warn("The 'box-forced' keyword argument is deprecated"
1314-
" since 2.2.", cbook.mplDeprecation, stacklevel=2)
1313+
cbook.warn_deprecated(
1314+
"2.2", "box-forced", obj_type="keyword argument")
13151315
if adjustable not in ('box', 'datalim', 'box-forced'):
13161316
raise ValueError("argument must be 'box', or 'datalim'")
13171317
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: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ def _generate_deprecation_message(
4242
if removal else
4343
"")))
4444
+ "."
45-
+ (" Use %(alternative)s instead." if alternative else ""))
45+
+ (" Use %(alternative)s instead." if alternative else "")
46+
+ (" %(addendum)s" if addendum else ""))
4647

4748
return (
4849
message % dict(func=name, name=name, obj_type=obj_type, since=since,
@@ -103,9 +104,9 @@ def warn_deprecated(
103104
obj_type='module')
104105
105106
"""
106-
message = _generate_deprecation_message(
107-
since, message, name, alternative, pending, obj_type, removal=removal)
108-
message = '\n' + message
107+
message = '\n' + _generate_deprecation_message(
108+
since, message, name, alternative, pending, obj_type, addendum,
109+
removal=removal)
109110
category = (PendingDeprecationWarning if pending
110111
else MatplotlibDeprecationWarning)
111112
warnings.warn(message, category, stacklevel=2)

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

@@ -277,8 +276,8 @@ def get_subplot_params(self, figure=None, fig=None):
277276
parameters are from rcParams unless a figure attribute is set.
278277
"""
279278
if fig is not None:
280-
warnings.warn("the 'fig' kwarg is deprecated "
281-
"use 'figure' instead", mplDeprecation)
279+
cbook.warn_deprecated("2.2", "fig", obj_type="keyword argument",
280+
alternative="figure")
282281
if figure is None:
283282
figure = fig
284283

@@ -367,8 +366,8 @@ def get_subplot_params(self, figure=None, fig=None):
367366
"""Return a dictionary of subplot layout parameters.
368367
"""
369368
if fig is not None:
370-
warnings.warn("the 'fig' kwarg is deprecated "
371-
"use 'figure' instead", mplDeprecation)
369+
cbook.warn_deprecated("2.2", "fig", obj_type="keyword argument",
370+
alternative="figure")
372371
if figure is None:
373372
figure = fig
374373

lib/matplotlib/tests/test_rcparams.py

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

454454
def test_if_rctemplate_is_up_to_date():
455455
# This tests if the matplotlibrc.template file contains all valid rcParams.
456-
deprecated = {*mpl._all_deprecated, *mpl._deprecated_set}
456+
deprecated = {*mpl._all_deprecated, *mpl._deprecated_remain_as_none}
457457
path_to_rc = os.path.join(mpl.get_data_path(), 'matplotlibrc')
458458
with open(path_to_rc, "r") as f:
459459
rclines = f.readlines()
@@ -472,8 +472,8 @@ def test_if_rctemplate_is_up_to_date():
472472
if not found:
473473
missing.update({k: v})
474474
if missing:
475-
raise ValueError("The following params are missing " +
476-
"in the matplotlibrc.template file: {}"
475+
raise ValueError("The following params are missing in the "
476+
"matplotlibrc.template file: {}"
477477
.format(missing.items()))
478478

479479

0 commit comments

Comments
 (0)