What do you think about when writing a new function in Python? The function name, parameter names, optional/required parameters, and default arguments

Strict Python function parameters

submited by
Style Pass
2022-01-23 14:30:03

What do you think about when writing a new function in Python? The function name, parameter names, optional/required parameters, and default arguments are all on the list. Here is a simple Python function that has all these covered:

However, there's one aspect many programmers have an opinion about but don't realize can be encoded into the function definition: How should callers specify each argument to the function? For the above function you'd likely document the following usages:

You don't need to specify data= for readers to infer what the first argument is likely to be. The parameter name is hinted by the function name: process_data(). On the other hand the encoding parameter isn't obvious if you only see the argument value. Given this I would recommend using a keyword argument for encoding.

The above decisions make sense to me having written lots of Python, but what about beginners to Python or the library? Function parameters don't explain "how" to pass arguments. Whether an argument is passed as a positional argument or keyword argument is usually up to the caller. Below are all the ways to specify the same parameters, but many are likely not what the author intended:

Leave a Comment