Functions: Deep Dive

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

More About Functions

Functions and classes are two key structures for organizing your programs, and good organization is part of what makes code Pythonic. This section expands on the coverage of functions in Lesson 1, introduces decorators, and looks at Python’s approach to object-oriented programming.

Nested Functions

Python supports nested functions, or functions inside functions, as shown in the code below:

Passing Functions as Arguments

In Python, everything is an object — functions included — meaning you can pass them as arguments to other functions. The code below defines two functions that take a number and perform a math operation on it, plus_5() and squared(), and calculate(), which takes a function and a number and applies that function to the number:

Defining Anonymous Functions

Python uses the keyword lambda to define anonymous functions — small unnamed functions typically used as arguments passed to functions.

Functions That Take a Variable Number of Arguments

So far, this module has covered only functions that take a fixed number of arguments, also known as fixed-arity functions. Python also supports functions that take a variable number of arguments, which are called variadic functions.

Decorators

Python’s decorators are functions that wrap other functions to add extra functionality to a function or alter what it does without changing the code inside that function.

Simple Decorators

Suppose you have these two functions:

See forum comments
Download course materials from Github
Previous: Comprehensions Next: Classes & Objects