6 Defining user-friendly functions

 

This chapter covers

  • Setting proper default arguments for a function
  • Setting and using the return value for a function
  • Applying type hints to the parameters and the return value
  • Defining functions with a variable number of positional and keyword arguments
  • Creating proper docstrings for a function

In previous chapters, you’ve seen several examples of functions. Broadly speaking, no matter what our applications are about, we define a wide range of functions to perform various operations, such as making calculations and formatting strings. When you work in a team environment, you often need to define functions that allow your team members to reuse your code. When you publish a Python package, the package should include well-defined functions for users like the built-in functions provided by the standard Python library. Thus, it’s an essential skill to define user-friendly functions; even if you work on your own, you don’t want functions to be hard to use.

When I say user-friendly functions, I mean functions that are easy to understand, with proper type hints for the arguments, and that are convenient to call, possibly using default arguments. For functions that are self-explanatory, users can locate the needed help information, usually in the form of docstrings.

6.1 How do I set default arguments to make function calls easier?

6.1.1 Calling functions with default arguments

6.1.2 Defining functions with default arguments

6.1.3 Avoiding the pitfall of setting default arguments for mutable parameters

6.1.4 Discussion

6.1.5 Challenge

6.2 How do I set and use the return value in function calls?

6.2.1 Returning a value implicitly or explicitly

6.2.2 Defining functions returning zero, one, or multiple values

6.2.3 Using multiple values returned from a function call

6.2.4 Discussion

6.2.5 Challenge

6.3 How do I use type hints to write understandable functions?

6.3.1 Providing type hinting to variables