Rodrigo ๐Ÿ๐Ÿš€
Rodrigo ๐Ÿ๐Ÿš€

@mathsppblog

5 Tweets 3 reads Mar 18, 2023
Python ๐Ÿ functions take positional and keyword arguments.
You can force your functions to only accept some arguments as positional-only and/or others as keyword-only. ๐Ÿš€
Here is how. ๐Ÿ‘‡๐Ÿงต
A regular parameter list only lists the names of the parameters.
That's as simple as it gets.
Then, you can pass in arguments by position and others by name.
HOWEVER, all the positional ones need to come before the named ones.
E.g., f(1, arg2=2, 3) will NOT work.
You can use `*` to force parameters to be keyword only.
All parameters to the right ๐Ÿ‘‰ of `*` must be passed in by name.
Use this, for example, when you have A LOT of parameters or when the final ones are options/configurations.
You can use `/` to force parameters to be positional only.
All parameters to the left ๐Ÿ‘ˆ of `/` must be passed in by position.
Use this, for example, when the first (few) parameters do not have obvious meaningful names.
Trivial example:
def add(a, b, /):
return a + b
Finally, `/` and `*` can be mixed together for maximum havoc!
To the left of `/`, positional-only.
To the right of `*`, keyword-only.
`*` must come after `/`, obviously...
And between `/` and `*`, you can do whatever you want!

Loading suggestions...