A decorator to add a 'data' kwarg to a function. When applied:: @_preprocess_data() def func(ax, *args, **kwargs): ... the signature is modified to ``decorated(ax, *args, data=None, **kwargs)`` with the following behavior: - if called with ``data=None``, forw
(func=None, *, replace_names=None, label_namer=None)
| 1450 | |
| 1451 | |
| 1452 | def _preprocess_data(func=None, *, replace_names=None, label_namer=None): |
| 1453 | """ |
| 1454 | A decorator to add a 'data' kwarg to a function. |
| 1455 | |
| 1456 | When applied:: |
| 1457 | |
| 1458 | @_preprocess_data() |
| 1459 | def func(ax, *args, **kwargs): ... |
| 1460 | |
| 1461 | the signature is modified to ``decorated(ax, *args, data=None, **kwargs)`` |
| 1462 | with the following behavior: |
| 1463 | |
| 1464 | - if called with ``data=None``, forward the other arguments to ``func``; |
| 1465 | - otherwise, *data* must be a mapping; for any argument passed in as a |
| 1466 | string ``name``, replace the argument by ``data[name]`` (if this does not |
| 1467 | throw an exception), then forward the arguments to ``func``. |
| 1468 | |
| 1469 | In either case, any argument that is a `MappingView` is also converted to a |
| 1470 | list. |
| 1471 | |
| 1472 | Parameters |
| 1473 | ---------- |
| 1474 | replace_names : list of str or None, default: None |
| 1475 | The list of parameter names for which lookup into *data* should be |
| 1476 | attempted. If None, replacement is attempted for all arguments. |
| 1477 | label_namer : str, default: None |
| 1478 | If set e.g. to "namer" (which must be a kwarg in the function's |
| 1479 | signature -- not as ``**kwargs``), if the *namer* argument passed in is |
| 1480 | a (string) key of *data* and no *label* kwarg is passed, then use the |
| 1481 | (string) value of the *namer* as *label*. :: |
| 1482 | |
| 1483 | @_preprocess_data(label_namer="foo") |
| 1484 | def func(foo, label=None): ... |
| 1485 | |
| 1486 | func("key", data={"key": value}) |
| 1487 | # is equivalent to |
| 1488 | func.__wrapped__(value, label="key") |
| 1489 | """ |
| 1490 | |
| 1491 | if func is None: # Return the actual decorator. |
| 1492 | return functools.partial( |
| 1493 | _preprocess_data, |
| 1494 | replace_names=replace_names, label_namer=label_namer) |
| 1495 | |
| 1496 | sig = inspect.signature(func) |
| 1497 | varargs_name = None |
| 1498 | varkwargs_name = None |
| 1499 | arg_names = [] |
| 1500 | params = list(sig.parameters.values()) |
| 1501 | for p in params: |
| 1502 | if p.kind is Parameter.VAR_POSITIONAL: |
| 1503 | varargs_name = p.name |
| 1504 | elif p.kind is Parameter.VAR_KEYWORD: |
| 1505 | varkwargs_name = p.name |
| 1506 | else: |
| 1507 | arg_names.append(p.name) |
| 1508 | data_param = Parameter("data", Parameter.KEYWORD_ONLY, default=None) |
| 1509 | if varkwargs_name: |
searching dependent graphs…