Helper functions for managing the Matplotlib API.

This documentation is only relevant for Matplotlib developers, not for users.


This module and its submodules are for internal use only. Do not use them in your own code. We may change the API at any time with no warning.


Helper decorator for implementing module-level __getattr__ as a class.

This decorator must be used at the module toplevel as follows:

class __getattr__:  # The class *must* be named ``__getattr__``.
    @property  # Only properties are taken into account.
    def name(self): ...

The __getattr__ class will be replaced by a __getattr__ function such that trying to access name on the module will resolve the corresponding property (which may be decorated e.g. with _api.deprecated for deprecating module globals). The properties are all implicitly cached. Moreover, a suitable AttributeError is generated and raised if no property with the given name exists.

matplotlib._api.check_getitem(mapping, /, **kwargs)[source]#

kwargs must consist of a single key, value pair. If key is in mapping, return mapping[value]; else, raise an appropriate ValueError.


>>> _api.check_getitem({"foo": "bar"}, arg=arg)
matplotlib._api.check_in_list(values, /, *, _print_supported_values=True, **kwargs)[source]#

For each key, value pair in kwargs, check that value is in values; if not, raise an appropriate ValueError.


Sequence of values to check on.

_print_supported_valuesbool, default: True

Whether to print values when raising ValueError.


key, value pairs as keyword arguments to find in values.


If any value in kwargs is not found in values.


>>> _api.check_in_list(["foo", "bar"], arg=arg, other_arg=other_arg)
matplotlib._api.check_isinstance(types, /, **kwargs)[source]#

For each key, value pair in kwargs, check that value is an instance of one of types; if not, raise an appropriate TypeError.

As a special case, a None entry in types is treated as NoneType.


>>> _api.check_isinstance((SomeClass, None), arg=arg)
matplotlib._api.check_shape(shape, /, **kwargs)[source]#

For each key, value pair in kwargs, check that value has the shape shape; 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.


To check for (N, 2) shaped arrays

>>> _api.check_shape((None, 2), arg=arg, other_arg=other_arg)
class matplotlib._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 the class that's passed as argument.


class C:
    def foo(cls):
        return cls.__name__

assert == "C"
property fget#
matplotlib._api.define_aliases(alias_d, cls=None)[source]#

Class decorator for defining property aliases.

Use as

@_api.define_aliases({"property": ["alias", ...], ...})
class C: ...

For each property, if the corresponding get_property is defined in the class so far, an alias named get_alias will be defined; the same will be done for setters. If neither the getter nor the setter exists, an exception will be raised.

The alias map is stored as the _alias_map attribute on the class and can be used by normalize_kwargs (which assumes that higher priority aliases come last).

matplotlib._api.kwarg_error(name, kw)[source]#

Generate a TypeError to be raised by function calls with wrong kwarg.


The name of the calling function.

kwstr or Iterable[str]

Either the invalid keyword argument name, or an iterable yielding invalid 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.


Yield cls and direct and indirect subclasses of cls.

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 (other than TypeError if the arguments passed do not match their signature).

select_matching_signature tries to call each of the functions in funcs with *args, **kwargs (in the order in which they are given). Calls that fail with a TypeError are silently skipped. As soon as a call succeeds, select_matching_signature returns its return value. If no function accepts *args, **kwargs, then the TypeError raised by the last failing call is re-raised.

Callers should normally make sure that any *args, **kwargs can only bind a single func (to avoid any ambiguity), although this is not checked by select_matching_signature.


select_matching_signature is intended to help implementing signature-overloaded functions. In general, such functions should be avoided, except for back-compatibility concerns. A typical use pattern is

def my_func(*args, **kwargs):
    params = select_matching_signature(
        [lambda old1, old2: locals(), lambda new: locals()],
        *args, **kwargs)
    if "old1" in params:
        old1, old2 = params.values()  # note that locals() is ordered.
        new, = params.values()
    # do things with params

which allows my_func to be called either with two parameters (old1 and old2) or a single one (new). Note that the new signature is given last, so that callers get a TypeError corresponding to the new signature if the arguments they passed in do not match any signature.

matplotlib._api.warn_external(message, category=None)[source]#

warnings.warn wrapper that sets stacklevel to "outside Matplotlib".

The original emitter of the warning can be obtained by patching this function back to warnings.warn, i.e. _api.warn_external = warnings.warn (or functools.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.


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.

exception matplotlib._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 parameter name of func is being deprecated.

The actual implementation of func should keep the name parameter in its signature, or accept a **kwargs argument (through which name would be passed).

Parameters that come after the deprecated parameter effectively become keyword-only (as they cannot be passed positionally without triggering the DeprecationWarning on the deprecated parameter), and should be marked as such after the deprecation period has passed and the deprecated parameter is removed.

Parameters other than since, name, and func are keyword-only and forwarded to warn_deprecated.


@_api.delete_parameter("3.1", "unused")
def func(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.


An unbound method, i.e. an expression of the form Class.method_name. Remember that within the body of a method, one can always use __class__ to refer to the class that is currently being defined.


Either an object of the class where method is defined, or a subclass of that class.

allow_emptybool, default: False

Whether to allow overrides by "empty" methods without emitting a warning.


Additional parameters passed to warn_deprecated to generate the deprecation warning; must at least include the "since" key.

class matplotlib._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:

class Foo:
    attr = _deprecate_privatize_attribute(*args, **kwargs)

where all parameters are forwarded to deprecated. This form makes attr a property which forwards read and write access to self._attr (same name but with a leading underscore), with a deprecation warning. Note that the attribute name is derived from the name this helper is assigned 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 go under @classmethod and @staticmethod (i.e., deprecated should directly decorate the underlying callable), but over @property.

When deprecating a class C intended to be used as a base class in a multiple inheritance hierarchy, C must define an __init__ method (if C instead inherited its __init__ from its own base class, then @deprecated would mess up __init__ inheritance when installing its own (deprecation-emitting) C.__init__).

Parameters are the same as for warn_deprecated, except that obj_type defaults to 'class' if decorating a class, 'attribute' if decorating a property, and 'function' otherwise.


def the_function_to_deprecate():
matplotlib._api.deprecation.make_keyword_only(since, name, func=None)[source]#

Decorator indicating that passing parameter name (or any of the following ones) positionally to func is being deprecated.

When used on a method that has a pyplot wrapper, this should be the outermost decorator, so that can access the original signature.

matplotlib._api.deprecation.rename_parameter(since, old, new, func=None)[source]#

Decorator indicating that parameter old of func is renamed to new.

The actual implementation of func should use new, not old. If old is passed to func, a DeprecationWarning is emitted, and its value is used, even if new is also passed by keyword (this is to simplify pyplot wrapper functions, which always pass new explicitly to the Axes method). If new is also passed but positionally, a TypeError will be raised by the underlying function during argument binding.


@_api.rename_parameter("3.1", "bad_name", "good_name")
def func(good_name): ...
matplotlib._api.deprecation.warn_deprecated(since, *, message='', name='', alternative='', pending=False, obj_type='', addendum='', removal='')[source]#

Display a standardized deprecation.


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 values of 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 deprecated API. The deprecation warning will tell the user about this alternative if provided.

pendingbool, optional

If True, uses a PendingDeprecationWarning instead of a DeprecationWarning. Cannot be used together with removal.

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), a removal version is automatically computed from since. Set to other Falsy values to not schedule a removal date. Cannot be used together with pending.


# To warn of the deprecation of "matplotlib.name_of_module"
warn_deprecated('1.4.0', name='matplotlib.name_of_module',