chapter six

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 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 the users, just like how we use the built-in functions provided by the standard Python library. Thus, it’s an essential skill for you to define functions that are user-friendly — even if you work on your own, you don't want the functions are hard to use.

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 Every function returns a variable, 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

6.3.2 Using type hinting in function definitions

6.3.3 Applying advanced type hinting skills to function definitions

6.3.4 Discussion

6.3.5 Challenge

6.4 How do I increase function flexibility with *args and **kwargs?

6.4.1 Knowing positional and keyword arguments

6.4.2 Accepting a variable number of positional arguments

6.4.3 Accepting a variable number of keyword arguments

6.4.4 Discussion