Nested function definitions

We can include anything inside a function definition, even another function definition. When we look at decorators in Chapter 13, Metaprogramming and Decorators, we'll see cases of a function which includes a nested function definition.

We can include import statements within a function definition. An import statement is only really executed once. There's a global collection of imported modules. The name, however, would be localized to the function doing the import.

The general advice is given in the Zen of Python poem by Tim Peters:

Flat is better than nested.

We'll generally strive to have functions defined in a relatively simple, flat sequence. We'll avoid nesting unless it's truly required, as it is when creating decorators. ...

Get Python Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.