Keywords: Python | Function Return | Multiple Values | Tuple Unpacking | Named Tuple
Abstract: This article comprehensively explores various methods for returning multiple values from Python functions, including tuple unpacking, named tuples, dictionaries, and custom classes. Through detailed code examples and practical scenario analysis, it helps developers understand the pros and cons of each approach and their suitable use cases, enhancing code readability and maintainability.
Introduction
In Python programming, it is often necessary to return multiple values from a function. Although Python syntax does not support directly returning multiple independent values, it provides several flexible ways to achieve this requirement. This article systematically introduces these methods with detailed code examples.
Tuple Unpacking Method
The most common approach is to return a tuple and unpack it at the call site. In Python, multiple values separated by commas automatically form a tuple.
def select_choice():
# Function logic processing
return i, card # Return tuple
When calling, multiple variables can be used to receive the return values:
my_i, my_card = select_choice()
This method is concise and efficient. Parentheses are optional; return i, card is equivalent to return (i, card). However, when returning more values, code readability may decrease.
Application of Named Tuples
For scenarios requiring multiple related return values, named tuples offer better readability. Named tuples allow accessing return values by field names while maintaining the lightweight nature of tuples.
from collections import namedtuple
ChoiceResult = namedtuple('ChoiceResult', ['i', 'card', 'other_field'])
def select_choice():
# Function logic
return ChoiceResult(i, card, other_field)
Usage with field name access:
result = select_choice()
print(result.i, result.card)
This method is widely used in frameworks like Marshmallow, where UnmarshalResult is implemented based on named tuples.
Dictionary Return Approach
When the number and structure of return values may vary, dictionaries provide maximum flexibility.
def select_choice():
# Function logic
return {
'i': i,
'card': card,
'other_field': other_field
}
Access via key names when calling:
result = select_choice()
print(result['i'], result['card'])
The advantage of this method is the ability to dynamically add fields, but it loses type safety and IDE auto-completion support.
Custom Class Encapsulation
For complex data structures, defining specialized classes to encapsulate return values is the best choice.
class ChoiceData:
def __init__(self, i, card, other_field):
self.i = i
self.card = card
self.other_field = other_field
def select_choice():
# Function logic
return ChoiceData(i, card, other_field)
Usage pattern:
choice_data = select_choice()
print(choice_data.i, choice_data.card)
This approach supports advanced features like data validation and method encapsulation, making it suitable for large-scale projects.
Practical Application Examples
The reference article's div_w_remainder function demonstrates multiple value returns in mathematical calculations:
def div_w_remainder(num, div):
quotient = int(num / div)
remainder = num % div
return quotient, remainder
q, r = div_w_remainder(17, 3)
print(f"Quotient: {q}, Remainder: {r}")
Another example is the list element location function:
def locate(x, item):
index_list = []
for i in range(len(x)):
if x[i] == item:
index_list.append(i)
return index_list, len(index_list)
These examples illustrate practical applications of multiple value returns in different scenarios.
Method Selection Guidelines
Choosing the appropriate method depends on specific requirements:
- Simple Scenarios: Use tuple unpacking for concise code
- Field Name Access Needed: Use named tuples to maintain lightness
- Dynamic Data Structures: Use dictionaries for high flexibility
- Complex Business Logic: Use custom classes to support extensibility
Conclusion
Python offers multiple flexible ways to return multiple values from functions. Developers should choose the appropriate method based on specific scenarios, balancing code conciseness, readability, and maintainability. Tuple unpacking is suitable for most simple cases, while named tuples, dictionaries, and custom classes are appropriate for different complex requirements.