As we have a one day's break from the Python functions series which returns with Day 10 tomorrow, let's look back the the topic from the last three days:

• positional-only arguments using / in function definitions
• keyword-only arguments using * in function definitions

/1

Why do we need them? Are they even ever used?

I bet you've seen them many times and ignored them. I'll go further and bet you've used them, too, without knowing

/2

Show thread

Have you ever used `list.sort()` with the `key` or `reverse` parameters?

I bet you have!

Here's the signature for `list.sort()`

sort(self, /, *, key=None, reverse=False)

/3

Show thread

>>> numbers = [4, 6, 7, 2]
>>> numbers.sort(reverse=True)
>>> numbers
[7, 6, 4, 2]

All fine here. But try to use a positional argument instead:

>>> numbers.sort(True)
Traceback (most recent call last):
...
TypeError: sort() takes no positional arguments

/4

Show thread

`key` and `reverse` are keyword-only in `list.sort()`

/5

Show thread

How about `str.replace()`? You've used that too?

Here's the signature:

replace(self, old, new, count=-1, /)

`old`, `new`, and `count` are all positional-only

/6

Show thread

Let's check:

>>> "hello".replace("l", '-')
'he--o'

>>> "hello".replace(old="l", new='-')
Traceback (most recent call last):
...
TypeError: str.replace() takes no keyword arguments

/7

Show thread

Maybe you use NumPy a lot? Positional-only and keyword-only arguments appear very often in the NumPy codebase

Here's just one example, NumPy's `mean()` method:

a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)

/8

Show thread

Or maybe you use Matplotlib? Here's `plt.scatter()`

Wait for it

scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, *, edgecolors=None, plotnonfinite=False, data=None, **kwargs)

Did you spot the lone * ?

/9

Show thread

They're easy to miss and ignore. But if you've read documentation, you will definitely have seen a * or a / in many function signatures

Now, when you see them next, you'll know perfectly well what they are and what they do

/10

Show thread

We'll return to the Python functions series tomorrow!

/11

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.