matplotlib._api
#
Helper functions for managing the Matplotlib API.
This documentation is only relevant for Matplotlib developers, not for users.
Warning
This module and its submodules are for internal use only. Do not use themin your own code. We may change the API at any time with no warning.
- matplotlib._api.caching_module_getattr(cls)[source]#
Helper decorator for implementing module-level
__getattr__
as a class.This decorator must be used at the module toplevel as follows:
@caching_module_getattrclass__getattr__:# The class *must* be named ``__getattr__``.@property# Only properties are taken into account.defname(self):...
The
__getattr__
class will be replaced by a__getattr__
function such that trying to accessname
on the module willresolve the corresponding property (which may be decorated e.g. with_api.deprecated
for deprecating module globals). The properties areall implicitly cached. Moreover, a suitable AttributeError is generatedand raised if no property with the given name exists.
- matplotlib._api.check_getitem(mapping,/,**kwargs)[source]#
kwargs must consist of a singlekey, value pair. Ifkey is inmapping, return
mapping[value]
; else, raise an appropriateValueError.Examples
>>>_api.check_getitem({"foo":"bar"},arg=arg)
- matplotlib._api.check_in_list(values,/,*,_print_supported_values=True,**kwargs)[source]#
For eachkey, value pair inkwargs, check thatvalue is invalues;if not, raise an appropriate ValueError.
- Parameters:
- valuesiterable
Sequence of values to check on.
- _print_supported_valuesbool, default: True
Whether to printvalues when raising ValueError.
- **kwargsdict
key, value pairs as keyword arguments to find invalues.
- Raises:
- ValueError
If anyvalue inkwargs is not found invalues.
Examples
>>>_api.check_in_list(["foo","bar"],arg=arg,other_arg=other_arg)
- matplotlib._api.check_isinstance(types,/,**kwargs)[source]#
For eachkey, value pair inkwargs, check thatvalue is an instanceof one oftypes; if not, raise an appropriate TypeError.
As a special case, a
None
entry intypes is treated as NoneType.Examples
>>>_api.check_isinstance((SomeClass,None),arg=arg)
- matplotlib._api.check_shape(shape,/,**kwargs)[source]#
For eachkey, value pair inkwargs, check thatvalue has the shapeshape;if not, raise an appropriate ValueError.
None in the shape is treated as a "free" size that can have any length.e.g. (None, 2) -> (N, 2)
The values checked must be numpy arrays.
Examples
To check for (N, 2) shaped arrays
>>>_api.check_shape((None,2),arg=arg,other_arg=other_arg)
- classmatplotlib._api.classproperty(fget,fset=None,fdel=None,doc=None)[source]#
Bases:
object
Like
property
, but also triggers on access via the class, and it is theclass that's passed as argument.Examples
classC:@classpropertydeffoo(cls):returncls.__name__assertC.foo=="C"
- propertyfget#
- matplotlib._api.define_aliases(alias_d,cls=None)[source]#
Class decorator for defining property aliases.
Use as
@_api.define_aliases({"property":["alias",...],...})classC:...
For each property, if the corresponding
get_property
is defined in theclass so far, an alias namedget_alias
will be defined; the same willbe done for setters. If neither the getter nor the setter exists, anexception will be raised.The alias map is stored as the
_alias_map
attribute on the class andcan be used bynormalize_kwargs
(which assumes that higher priorityaliases come last).
- matplotlib._api.kwarg_error(name,kw)[source]#
Generate a TypeError to be raised by function calls with wrong kwarg.
- Parameters:
- namestr
The name of the calling function.
- kwstr or Iterable[str]
Either the invalid keyword argument name, or an iterable yieldinginvalid keyword arguments (e.g., a
kwargs
dict).
- matplotlib._api.nargs_error(name,takes,given)[source]#
Generate a TypeError to be raised by function calls with wrong arity.
- matplotlib._api.recursive_subclasses(cls)[source]#
Yieldcls and direct and indirect subclasses ofcls.
- matplotlib._api.select_matching_signature(funcs,*args,**kwargs)[source]#
Select and call the function that accepts
*args,**kwargs
.funcs is a list of functions which should not raise any exception (otherthan
TypeError
if the arguments passed do not match their signature).select_matching_signature
tries to call each of the functions infuncswith*args,**kwargs
(in the order in which they are given). Callsthat fail with aTypeError
are silently skipped. As soon as a callsucceeds,select_matching_signature
returns its return value. If nofunction accepts*args,**kwargs
, then theTypeError
raised by thelast failing call is re-raised.Callers should normally make sure that any
*args,**kwargs
can onlybind a singlefunc (to avoid any ambiguity), although this is not checkedbyselect_matching_signature
.Notes
select_matching_signature
is intended to help implementingsignature-overloaded functions. In general, such functions should beavoided, except for back-compatibility concerns. A typical use pattern isdefmy_func(*args,**kwargs):params=select_matching_signature([lambdaold1,old2:locals(),lambdanew:locals()],*args,**kwargs)if"old1"inparams:warn_deprecated(...)old1,old2=params.values()# note that locals() is ordered.else:new,=params.values()# do things with params
which allowsmy_func to be called either with two parameters (old1 andold2) or a single one (new). Note that the new signature is givenlast, so that callers get a
TypeError
corresponding to the new signatureif the arguments they passed in do not match any signature.
- matplotlib._api.warn_external(message,category=None)[source]#
warnings.warn
wrapper that setsstacklevel to "outside Matplotlib".The original emitter of the warning can be obtained by patching thisfunction back to
warnings.warn
, i.e._api.warn_external=warnings.warn
(orfunctools.partial(warnings.warn,stacklevel=2)
,etc.).
Helper functions for deprecating parts of the Matplotlib API.
This documentation is only relevant for Matplotlib developers, not for users.
Warning
This module is for internal use only. Do not use it in your own code.We may change the API at any time with no warning.
- exceptionmatplotlib._api.deprecation.MatplotlibDeprecationWarning[source]#
Bases:
DeprecationWarning
A class for issuing deprecation warnings for Matplotlib users.
- matplotlib._api.deprecation.delete_parameter(since,name,func=None,**kwargs)[source]#
Decorator indicating that parametername offunc is being deprecated.
The actual implementation offunc should keep thename parameter in itssignature, or accept a
**kwargs
argument (through whichname would bepassed).Parameters that come after the deprecated parameter effectively becomekeyword-only (as they cannot be passed positionally without triggering theDeprecationWarning on the deprecated parameter), and should be marked assuch after the deprecation period has passed and the deprecated parameteris removed.
Parameters other thansince,name, andfunc are keyword-only andforwarded to
warn_deprecated
.Examples
@_api.delete_parameter("3.1","unused")deffunc(used_arg,other_arg,unused,more_args):...
- matplotlib._api.deprecation.deprecate_method_override(method,obj,*,allow_empty=False,**kwargs)[source]#
Return
obj.method
with a deprecation if it was overridden, else None.- Parameters:
- method
An unbound method, i.e. an expression of the form
Class.method_name
. Remember that within the body of a method, onecan always use__class__
to refer to the class that is currentlybeing defined.- obj
Either an object of the class wheremethod is defined, or a subclassof that class.
- allow_emptybool, default: False
Whether to allow overrides by "empty" methods without emitting awarning.
- **kwargs
Additional parameters passed to
warn_deprecated
to generate thedeprecation warning; must at least include the "since" key.
- classmatplotlib._api.deprecation.deprecate_privatize_attribute(*args,**kwargs)[source]#
Bases:
object
Helper to deprecate public access to an attribute (or method).
This helper should only be used at class scope, as follows:
classFoo:attr=_deprecate_privatize_attribute(*args,**kwargs)
whereall parameters are forwarded to
deprecated
. This form makesattr
a property which forwards read and write access toself._attr
(same name but with a leading underscore), with a deprecation warning.Note that the attribute name is derived fromthe name this helper isassigned to. This helper also works for deprecating methods.
- matplotlib._api.deprecation.deprecated(since,*,message='',name='',alternative='',pending=False,obj_type=None,addendum='',removal='')[source]#
Decorator to mark a function, a class, or a property as deprecated.
When deprecating a classmethod, a staticmethod, or a property, the
@deprecated
decorator should gounder@classmethod
and@staticmethod
(i.e.,deprecated
should directly decorate theunderlying callable), butover@property
.When deprecating a class
C
intended to be used as a base class in amultiple inheritance hierarchy,C
must define an__init__
method(ifC
instead inherited its__init__
from its own base class, then@deprecated
would mess up__init__
inheritance when installing itsown (deprecation-emitting)C.__init__
).Parameters are the same as for
warn_deprecated
, except thatobj_typedefaults to 'class' if decorating a class, 'attribute' if decorating aproperty, and 'function' otherwise.Examples
@deprecated('1.4.0')defthe_function_to_deprecate():pass
- matplotlib._api.deprecation.make_keyword_only(since,name,func=None)[source]#
Decorator indicating that passing parametername (or any of the followingones) positionally tofunc is being deprecated.
When used on a method that has a pyplot wrapper, this should be theoutermost decorator, so that
boilerplate.py
can access the originalsignature.
- matplotlib._api.deprecation.rename_parameter(since,old,new,func=None)[source]#
Decorator indicating that parameterold offunc is renamed tonew.
The actual implementation offunc should usenew, notold. Ifoldis passed tofunc, a DeprecationWarning is emitted, and its value isused, even ifnew is also passed by keyword (this is to simplify pyplotwrapper functions, which always passnew explicitly to the Axes method).Ifnew is also passed but positionally, a TypeError will be raised by theunderlying function during argument binding.
Examples
@_api.rename_parameter("3.1","bad_name","good_name")deffunc(good_name):...
- matplotlib._api.deprecation.warn_deprecated(since,*,message='',name='',alternative='',pending=False,obj_type='',addendum='',removal='')[source]#
Display a standardized deprecation.
- Parameters:
- sincestr
The release at which this API became deprecated.
- messagestr, optional
Override the default deprecation message. The
%(since)s
,%(name)s
,%(alternative)s
,%(obj_type)s
,%(addendum)s
,and%(removal)s
format specifiers will be replaced by the valuesof the respective arguments passed to this function.- namestr, optional
The name of the deprecated object.
- alternativestr, optional
An alternative API that the user may use in place of the deprecatedAPI. The deprecation warning will tell the user about this alternativeif provided.
- pendingbool, optional
If True, uses a PendingDeprecationWarning instead of aDeprecationWarning. Cannot be used together withremoval.
- obj_typestr, optional
The object type being deprecated.
- addendumstr, optional
Additional text appended directly to the final message.
- removalstr, optional
The expected removal version. With the default (an empty string), aremoval version is automatically computed fromsince. Set to otherFalsy values to not schedule a removal date. Cannot be used togetherwithpending.
Examples
# To warn of the deprecation of "matplotlib.name_of_module"warn_deprecated('1.4.0',name='matplotlib.name_of_module',obj_type='module')