With a function f
calling another well-known function in Python (e.g. a matplotlib
function), what is the most pythonic/efficient/elegant way to define some default values while still giving the possibility to the user of f
to fully customize the called function (typically with **kwargs
), including to overwrite the default keyword arguments defined in f
?
import numpy as np
import matplotlib.pyplot as plt
v = np.linspace(-10.,10.,100)
x,y = np.meshgrid(v, v)
z = -np.hypot(x, y)
def f(ax, n=12, **kwargs):
ax.contourf(x, y, z, n, cmap=plt.cm.autumn, **kwargs)
fig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(2, 2)
f(ax0) # OK
f(ax1, n=100) # OK
f(ax2, n=100, **{'vmax': -2, 'alpha': 0.2}) # OK
# f(ax3, n=100, **{'cmap': plt.cm.cool}) # ERROR
plt.show()
Here, the last call to f
throws:
TypeError: contourf() got multiple values for keyword argument 'cmap'
In your wrapper, you could simply adjust kwargs
before passing it to wrapped function:
def f(ax, n=12, **kwargs):
kwargs.setdefault('cmap', plt.cm.autumn)
ax.contourf(x, y, z, n, **kwargs)
setdefault
will avoid changing the argument if it was passed to your wrapper, but you could just as easily always clobber it if you wanted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With