2

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.

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

Just do the following:

def pprint(x, **kwargs):
    sub = kwargs.get('sub', False)
    headers = kwargs.get('headers', [])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.