␡
- 5.1 Function Definitions
- 5.2 Default Arguments
- 5.3 Variadic Arguments
- 5.4 Keyword Arguments
- 5.5 Variadic Keyword Arguments
- 5.6 Functions Accepting All Inputs
- 5.7 Positional-Only Arguments
- 5.8 Names, Documentation Strings, and Type Hints
- 5.9 Function Application and Parameter Passing
- 5.10 Return Values
- 5.11 Error Handling
- 5.12 Scoping Rules
- 5.13 Recursion
- 5.14 The lambda Expression
- 5.15 Higher-Order Functions
- 5.16 Argument Passing in Callback Functions
- 5.17 Returning Results from Callbacks
- 5.18 Decorators
- 5.19 Map, Filter, and Reduce
- 5.20 Function Introspection, Attributes, and Signatures
- 5.21 Environment Inspection
- 5.22 Dynamic Code Execution and Creation
- 5.23 Asynchronous Functions and await
- 5.24 Final Words: Thoughts on Functions and Composition
This chapter is from the book
5.10 Return Values
The return statement returns a value from a function. If no value is specified or you omit the return statement, None is returned. To return multiple values, place them in a tuple:
def parse_value(text): ''' Split text of the form name=val into (name, val) ''' parts = text.split('=', 1) return (parts[0].strip(), parts[1].strip())
Values returned in a tuple can be unpacked to individual variables:
name, value = parse_value('url=http://www.python.org')
Sometimes named tuples are used as an alternative:
from typing import NamedTuple class ParseResult(NamedTuple): name: str value: str def parse_value(text): ''' Split text of the form name=val into (name, val) ''' parts = text.split('=', 1) return ParseResult(parts[0].strip(), parts[1].strip())
A named tuple works the same way as a normal tuple (you can perform all the same operations and unpacking), but you can also reference the returned values using named attributes:
r = parse_value('url=http://www.python.org') print(r.name, r.value)