Skip to content

Functions

Alejandra Rodriguez Garcia edited this page Oct 23, 2022 · 22 revisions

A series of statements which returns some value to a caller. It can also be passed zero or more arguments which may be used in the execution of the body. See also parameter, method, and the Function definitions section.
-- Python docs

imagen

Return

All functions calls return one object, although that object might be None (signifying no value) or a tuple containing multiple elements (signifying multiple values).

If there is no return statement, or just a bare return, the object returned is None.

Sometimes, it's correct to return multiple values from a function. For this, you can return a tuple of values.

Generator Functions

A generatot funcion is defined as a special type of function that contains the keyword yield. Thif function can produce a stream of values when called. A generator function looks like a normal function, except it contains the keyword yield. When called, a generator function returns a generator iterator that can produce subsequent values on demand by running the function until it encounters a yield statement, and then pausing. In this way, generators are an advanced way to describe a stream of data.

Function scope

Keyword arguments

Variadic Arguments

So far, we've seen that arguments can be supplied either by position or by name, and that arguments are matched to named parameters (which might have default values) from the function signature when the function is invoked. What happens if we want to capture an argument that we don't expect?

Variadic parameters are Python's answer to that question. A variadic parameter collection collects excess arguments (that would otherwise go unmatched to a parameter) into a data structure, for the function implementation's use. We'll see two kinds of variadic parameters: variadic positional parameters and variadic keyword parameters.

  • Variadic Keyword Argument Unpacking: A mechanism to unpack an mapping with the syntax mapping into keyword arguments supplied when a function is invoked.

variadic keyword parameters

A parameter of the form name (such askwargs) in a function signature introduces a variadic keyword parameter. This parameter will capture excess keyword-supplied arguments into a dictionary named the same thing, such as kwargs.

Why would you ever do something like this? Usually, variadic keyword parameters are useful when you're either:

  • Allowing arbitrary named parameters for special configuration
  • As with variadic positional parameters, capturing an unknown collection of arguments, in order to forward them to another handler, like a superclass, a decorator, or other fancy objects.

Variadic keyword parameters are a bit less common, but still appear throughout Python.

  • Variadic Keyword Parameter Collection: A category of parameter like kwargs that captures a variable number of excess keyword arguments in a dictionary.

imagen imagen

Lambda Functions

Lambda functions are anonymous, on-the-fly functions that are used for simple callables that don't need to clutter the local namespace.

Pros:


Being anonymous, lambda functions can be easily passed without being assigned to a variable. Lambda functions are inline functions and thus execute comparatively faster. Many times lambda functions make code much more readable by avoiding the logical jumps caused by function calls. cons:


Lambda functions can have only one expression. Lambda functions cannot have a docstring. Many times lambda functions make code difficult to read.

imagen

Stlye

https://peps.python.org/pep-0257/ PEP 257 - Docstring Conventions PEP 8 - Style Guide for Python Code

Decorators

def print_args(function):
def wrapper(*args, **kwargs):
print(args, kwargs)
return function(*args, **kwargs)
return wrapper
imagen

This decorator captures a function, and creates and returns a new function named wrapper. The wrapper function captures any collection of arguments, prints them out, and then forwards them to the supplied function. Let's take a look at this decorator in action

imagen


Function Behavior

Return values: Functions always return some value, even if that value is None or a tuple.
Scope: Functions introduce new scopes; assignment is to the local scope; name resolution happens from the local scope outwards (local (-> enclosing) -> global -> built-in)
Pass-by-object-reference: The literal names of the arguments are copied by value into the function's local namespace, but each name is just a reference to an object. In this way, Python passes object-references into functions.

Arguments

Keyword arguments are used to provide default, optional parameters, and are super useful to present a simple interface while maintaining the power of configurability and more complex implementation.
Variadic arguments (positional and keyword) capture excess arguments into a collection for processing or forwarding to another handler.

Functional programming

map and filter are functional tools to transform or filter collections.
lambda functions are on-the-fly anonymous functions for simple applications.
Iterators provide the abstraction of a stream of data.
Generator functions (or even generator expressions) provide more control over defining a stream of data.
Refactoring Python code to use generators is a nice way to simplify programs where there is a lot of data flowing around.

Decorators

Decorators are high-level functional transformations.
The @decorator syntax above a function definition immediately applies the decorator to the function object after definition.
Decorators are useful for a plethora of behavior modifications, from memoization to timeouts to network abstractions.

Excercises

In this exercise, you'll write a function named create_profile. This function should require at least one positional argument (someone's given name, and a variadic collection of surnames or modifiers) and must handle a variadic collection of keyword-specified arguments with details from a profile.

You'll need to define the function signature so that it can be called in the following valid ways:

create_profile('Sam') create_profile('Sam', role='Instructor') create_profile('Martin', 'Luther', 'King', 'Jr', born=1929, died=1968) create_profile("Sebastian", "Thrun", cofounded="Udacity", experience="Stanford Professor")

imagen

imagen

Reference

https://docs.python.org/3/tutorial/controlflow.html#defining-functions https://realpython.com/python-return-statement/ https://docs.python.org/3/tutorial/controlflow.html#function-examples https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists https://youtu.be/5W1mQ1XniYY?t=14

imagen

Udacity.com

Clone this wiki locally