GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — matplotlib/lib/matplotlib/_api/__init__.py at v3.11.2 · matplotlib/matplotlib Expand file tree/ Copy path__init__.pyMore file actions 494 lines (399 loc) · 17 KB / Copy path__init__.pyFile metadata and controls494 lines (399 loc) · 17 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 """ 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 them in your own code. We may change the API at any time with no warning. """ import difflib import functools import itertools import pathlib import re import sys import warnings from .deprecation import ( # noqa: F401 deprecated, warn_deprecated, rename_parameter, delete_parameter, make_keyword_only, deprecate_method_override, deprecate_privatize_attribute, suppress_matplotlib_deprecation_warning, MatplotlibDeprecationWarning) # A sentinel value for optional arguments, when None cannot be used as # default because we need to distinguish between None passed explicitly # and parameter not given. Usage: def foo(arg=_api.UNSET): class _Unset: def __repr__(self): return "<UNSET>" UNSET = _Unset() class UnsupportedError(RuntimeError): """ Raised on inherited methods if the child class does not support the functionality of the base class. See `.unsupported_method` for details. """ class unsupported_method: """ Descriptor that creates a method raising `.UnsupportedError`. Historically, we have quite a few cases of inheritance hierarchies that do not fully respect the Liskov Substitution Principle, e.g. Axes and Artist. Some of the methods of a base class may not be implemented in the child class. In that case, we override the method in the child class to raise `.UnsupportedError`. Use in a class body to mark inherited methods as unsupported:: class Axes3D(Axes): twinx = _api.unsupported_method() Calling ``Axes3D().twinx()`` will raise "UnsupportedError: Axes3D does not support 'twinx'." Parameters ---------- append_message : str Optional additional text to be appended to the error message. """ def __init__(self, *, append_message=None): self.append_message = append_message def __set_name__(self, owner, name): message = f"{owner.__name__} does not support '{name}'." if self.append_message: message += ' ' + self.append_message def method(self, *args, **kwargs): raise UnsupportedError(message) method.__name__ = name method.__qualname__ = f"{owner.__qualname__}.{name}" method.__module__ = owner.__module__ setattr(owner, name, method) class classproperty: """ Like `property`, but also triggers on access via the class, and it is the *class* that's passed as argument. Examples -------- :: class C: @classproperty def foo(cls): return cls.__name__ assert C.foo == "C" """ def __init__(self, fget, fset=None, fdel=None, doc=None): self._fget = fget if fset is not None or fdel is not None: raise ValueError('classproperty only implements fget.') self.fset = fset self.fdel = fdel # docs are ignored for now self._doc = doc def __get__(self, instance, owner): return self._fget(owner) @property def fget(self): return self._fget # In the following check_foo() functions, the first parameter is positional-only to make # e.g. `_api.check_isinstance([...], types=foo)` work. def check_isinstance(types, /, **kwargs): """ 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. Examples -------- >>> _api.check_isinstance((SomeClass, None), arg=arg) """ none_type = type(None) types = ((types,) if isinstance(types, type) else (none_type,) if types is None else tuple(none_type if tp is None else tp for tp in types)) def type_name(tp): return ("None" if tp is none_type else tp.__qualname__ if tp.__module__ == "builtins" else f"{tp.__module__}.{tp.__qualname__}") for k, v in kwargs.items(): if not isinstance(v, types): names = [*map(type_name, types)] if "None" in names: # Move it to the end for better wording. names.remove("None") names.append("None") raise TypeError( "{!r} must be an instance of {}, not a {}".format( k, ", ".join(names[:-1]) + " or " + names[-1] if len(names) > 1 else names[0], type_name(type(v)))) def list_suggestion_error_msg(name, potential, values): """ Generate an error message that a potential setting is not an acceptable value. If the acceptable values are all strings, and sufficiently large, then add just a few suggestions to the end of the message. Otherwise list the supported values. Parameters ---------- name : str The name of the setting, keyword argument, etc. to generate the message for. potential The potential value from the user that is not a valid choice. values : iterable Sequence of values to check on. """ if len(values) > 5 and all(isinstance(v, str) for v in [potential, *values]): best = difflib.get_close_matches(potential, values, cutoff=0.5) match len(best): case 0: suggestion = "" case 1: suggestion = f" Did you mean: {best[0]!r}?" case _: suggestion = f" Did you mean one of: {', '.join(map(repr, best))}?" else: suggestion = f" Supported values are {', '.join(map(repr, values))}" return f"{potential!r} is not a valid value for {name}.{suggestion}" def check_in_list(values, /, **kwargs): """ For each *key, value* pair in *kwargs*, check that *value* is in *values*; if not, raise an appropriate ValueError. Parameters ---------- values : iterable Sequence of values to check on. Note: All values must support == comparisons. This means in particular the entries must not be numpy arrays. **kwargs : dict *key, value* pairs as keyword arguments to find in *values*. Raises ------ ValueError If any *value* in *kwargs* is not found in *values*. Examples -------- >>> _api.check_in_list(["foo", "bar"], arg=arg, other_arg=other_arg) """ if not kwargs: raise TypeError("No argument to check!") for key, val in kwargs.items(): try: exists = val in values except ValueError: # `in` internally uses `val == values[i]`. There are some objects # that do not support == to arbitrary other objects, in particular # numpy arrays. # Since such objects are not allowed in values, we can gracefully # handle the case that val (typically provided by users) is of such # type and directly state it's not in the list instead of letting # the individual `val == values[i]` ValueError surface. exists = False if not exists: raise ValueError(list_suggestion_error_msg(key, val, values)) def check_shape(shape, /, **kwargs): """ 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. Examples -------- To check for (N, 2) shaped arrays >>> _api.check_shape((None, 2), arg=arg, other_arg=other_arg) """ for k, v in kwargs.items(): data_shape = v.shape if (len(data_shape) != len(shape) or any(s != t and t is not None for s, t in zip(data_shape, shape))): dim_labels = iter(itertools.chain( 'NMLKJIH', (f"D{i}" for i in itertools.count()))) text_shape = ", ".join([str(n) if n is not None else next(dim_labels) for n in shape[::-1]][::-1]) if len(shape) == 1: text_shape += "," raise ValueError( f"{k!r} must be {len(shape)}D with shape ({text_shape}), " f"but your input has shape {v.shape}" ) def getitem_checked(mapping, /, _error_cls=ValueError, **kwargs): """ *kwargs* must consist of a single *key, value* pair. If *key* is in *mapping*, return ``mapping[value]``; else, raise an appropriate ValueError. Parameters ---------- _error_cls : Class of error to raise. Examples -------- >>> _api.getitem_checked({"foo": "bar"}, arg=arg) """ if len(kwargs) != 1: raise ValueError("getitem_checked takes a single keyword argument") (k, v), = kwargs.items() try: return mapping[v] except KeyError: raise _error_cls(list_suggestion_error_msg(k, v, mapping.keys())) from None def caching_module_getattr(cls): """ Helper decorator for implementing module-level ``__getattr__`` as a class. This decorator must be used at the module toplevel as follows:: @caching_module_getattr 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. """ assert cls.__name__ == "__getattr__" # Don't accidentally export cls dunders. props = {name: prop for name, prop in vars(cls).items() if isinstance(prop, property)} instance = cls() @functools.cache def __getattr__(name): if name in props: return props[name].__get__(instance) raise AttributeError( f"module {cls.__module__!r} has no attribute {name!r}") return __getattr__ def define_aliases(alias_d, cls=None): """ 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_to_prop`` attribute under the format ``{"alias": "property", ...}` on the class, and can be used by `.normalize_kwargs`. """ if cls is None: # Return the actual class decorator. return functools.partial(define_aliases, alias_d) def make_alias(name): # Enforce a closure over *name*. @functools.wraps(getattr(cls, name)) def method(self, *args, **kwargs): return getattr(self, name)(*args, **kwargs) return method for prop, aliases in alias_d.items(): exists = False for prefix in ["get_", "set_"]: if prefix + prop in vars(cls): exists = True for alias in aliases: method = make_alias(prefix + prop) method.__name__ = prefix + alias method.__doc__ = f"Alias for `{prefix + prop}`." setattr(cls, prefix + alias, method) if not exists: raise ValueError( f"Neither getter nor setter exists for {prop!r}") alias_to_prop = { alias: prop for prop, aliases in alias_d.items() for alias in aliases} def get_aliased_and_aliases(d): return {*d.keys(), *d.values()} preexisting_aliases = getattr(cls, "_alias_to_prop", {}) conflicting = (get_aliased_and_aliases(preexisting_aliases) & get_aliased_and_aliases(alias_to_prop)) if conflicting: # Need to decide on conflict resolution policy. raise NotImplementedError( f"Parent class already defines conflicting aliases: {conflicting}") cls._alias_to_prop = {**preexisting_aliases, **alias_to_prop} return cls def select_matching_signature(funcs, *args, **kwargs): """ 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`. Notes ----- `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: warn_deprecated(...) old1, old2 = params.values() # note that locals() is ordered. else: 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. """ # Rather than relying on locals() ordering, one could have just used func's # signature (``bound = inspect.signature(func).bind(*args, **kwargs); # bound.apply_defaults(); return bound``) but that is significantly slower. for i, func in enumerate(funcs): try: return func(*args, **kwargs) except TypeError: if i == len(funcs) - 1: raise def nargs_error(name, takes, given): """Generate a TypeError to be raised by function calls with wrong arity.""" return TypeError(f"{name}() takes {takes} positional arguments but " f"{given} were given") def kwarg_error(name, kw): """ Generate a TypeError to be raised by function calls with wrong kwarg. Parameters ---------- name : str The name of the calling function. kw : str or Iterable[str] Either the invalid keyword argument name, or an iterable yielding invalid keyword arguments (e.g., a ``kwargs`` dict). """ if not isinstance(kw, str): kw = next(iter(kw)) return TypeError(f"{name}() got an unexpected keyword argument '{kw}'") def recursive_subclasses(cls): """Yield *cls* and direct and indirect subclasses of *cls*.""" yield cls for subcls in cls.__subclasses__(): yield from recursive_subclasses(subcls) def warn_external(message, category=None): """ `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.). """ kwargs = {} if sys.version_info[:2] >= (3, 12): # Go to Python's `site-packages` or `lib` from an editable install. basedir = pathlib.Path(__file__).parents[2] kwargs['skip_file_prefixes'] = (str(basedir / 'matplotlib'), str(basedir / 'mpl_toolkits')) else: frame = sys._getframe() for stacklevel in itertools.count(1): if frame is None: # when called in embedded context may hit frame is None kwargs['stacklevel'] = stacklevel break if not re.match(r"\A(matplotlib|mpl_toolkits)(\Z|\.(?!tests\.))", # Work around sphinx-gallery not setting __name__. frame.f_globals.get("__name__", "")): kwargs['stacklevel'] = stacklevel break frame = frame.f_back # preemptively break reference cycle between locals and the frame del frame warnings.warn(message, category, **kwargs) |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |