Reputation: 1698
Just wondering if it is possible to use both an optional argument in the same function as multiple arguments. I've looked around and I feel as if I just have the vocabulary wrong or something. Example:
def pprint(x, sub = False, *Headers):
pass
Can I call it still using the multiple headers without having to always put True
or False
in for sub? I feel like it's a no because Headers
wouldn't know where it begins. I'd like to explicitly state that sub = True
otherwise it defaults to False
.
Upvotes: 2
Views: 63
Reputation: 464
Just do the following:
def pprint(x, **kwargs):
sub = kwargs.get('sub', False)
headers = kwargs.get('headers', [])
Upvotes: 0
Reputation: 2058
I want to say yes because lots of matplotlib (for example) methods have something similar to this...
For example,
matplotlib.pyplot.xcorr(x, y, normed=True, detrend=<function detrend_none at 0x2523ed8>, usevlines=True, maxlags=10, hold=None, **kwargs)
When I'm using this I can specify any of the keyword arguments by saying maxlags=20
for example. You do have to specify all the non-keyworded arguments (so x
in your case) before the keyword arguments.
Upvotes: 0
Reputation: 1121972
In Python 3, use:
def pprint(x, *headers, sub=False):
pass
putting the keyword arguments after the positionals. This syntax will not work in Python 2.
Demo:
>>> def pprint(x, *headers, sub=False):
... print(x, headers, sub)
...
>>> pprint('foo', 'bar', 'baz', sub=True)
foo ('bar', 'baz') True
>>> pprint('foo', 'bar', 'baz')
foo ('bar', 'baz') False
You must specify a different value for sub
using a keyword argument when calling the pprint()
function defined here.
Upvotes: 6