3

I would like to write a function that passes different keyword arguments to different functions.

For example, I want to write a function that plots a histogram of my data by first creating axes via gca and then adding the histogram via hist. I would like the user to be able to pass additional keyword arguments to both gca and hist.

Something like this (syntax error in the defintion line) is what I'm looking for,

import matplotlib.pyplot as plt def plot_hist(data, **kwargs_hist, **kwargs_gca): ax = plt.gca(**kwargs_gca) fig = ax.hist(data, **kwargs_hist)[0] return fig 
6
  • 1
    how would python know which keywords to pass to each function? Especially considering that inspect.signature(plt.gca) -> <Signature (**kwargs)> Commented May 27, 2016 at 16:25
  • What is it that defines where the keyword argument goes? Commented May 27, 2016 at 16:27
  • @tadhg That's exactly the problem I'm trying to solve. Am I able to accomplish something like this? Commented May 27, 2016 at 16:28
  • @zondo I would like the user to decide which optional arguments to pass to hist and which to gca Commented May 27, 2016 at 16:30
  • 4
    well you could just have the user pass two dictionaries instead of keywords, then you would call it like plot_hist(DATA, dict(var1=1, var2=2), dict(var3=3, var4=4)) and just remove the ** in the definition line. Commented May 27, 2016 at 16:31

1 Answer 1

2

Without knowing exactly which keyword arguments to delegate to each function the **keywords just isn't going to work in this scenario, you can instead take two dictionaries for the keywords to each function as arguments:

def plot_hist(data, kwargs_hist={}, kwargs_gca={}): ax = plt.gca(**kwargs_gca) fig = ax.hist(data, **kwargs_hist)[0] return fig 

and then make the separate dictionaries, the keyword syntax can still be used by passing them to the dict constructor:

plot_hist(DATA, dict(hist_arg=3, foo=6), dict(gca_arg=1, bar = 4)) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.