How can I mix multiple and optional arguments in Python?
I want to write a function with default parameters and multiple arguments. Now I have something like this:
def make_pizza(size=10, *toppings):
for t in toppings:
print("-",t)
print('Pizza has', size, 'cm')
and then I try to call:
make_pizza(30, 'pepperoni')
make_pizza('pepperoni')
make_pizza(50, 'cheese', 'cucumber', 'chilli')
but the results look bad:
- pepperoni
Pizza has 30 cm
Pizza has pepperoni cm
- cheese
- cucumber
- chilli
Pizza has 50 cm
What if I want to print '10' instead of pepperoni on the third line?
source to share
Ok, since you are using Python 3, the easiest is to have a size
keyword-only argument :
def make_pizza(*toppings, size=10):
for t in toppings:
print("-",t)
print('Pizza has', size, 'cm')
Please note what size=10
follows *toppings
.
Now, to specify size
, you need to explicitly specify it:
make_pizza('pepperoni')
make_pizza('pepperoni', size=30)
Another alternative could be type checking size
, and if it is an instance numbers.Number
then suppose it is the size, otherwise it is top and should be added to the beginning of the tuple toppings
... and the size should be reset to default.
Or you can always specify the size.
However, I would prefer keyword-only arguments as this is exactly the problem they were supposed to solve.
source to share