- What’s the best way to return multiple values from a function? [duplicate]
- 6 Answers 6
- Linked
- Related
- Hot Network Questions
- Как вернуть сразу несколько значений из функции в Python 3
- Способ 1: возврат значений с помощью словарей
- Способ 2: возврат значений с помощью списков
- Способ 3: возврат значений с помощью кортежей
- Способ 4: возврат значений с помощью объектов
- Способ 5: возврат значений с помощью классов данных (Python 3.7+)
- Вывод
- Elegant ways to return multiple values from a function
- 14 Answers 14
What’s the best way to return multiple values from a function? [duplicate]
I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string. In C#, I would use an out parameter for the string, but there is no equivalent in Python. I’m still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string. Related question: Is it pythonic for a function to return multiple values?
6 Answers 6
def f(in_str): out_str = in_str.upper() return True, out_str # Creates tuple automatically succeeded, b = f("a") # Automatic tuple unpacking
Why not throw an exception if the operation wasn’t successful? Personally, I tend to be of the opinion that if you need to return more than one value from a function, you should reconsider if you’re doing things the right way or use an object.
But more directly to the point, if you throw an exception, you’re forcing them to deal with the problem. If you try to return a value that indicates failure, it’s very well possible somebody could not check the value and end up with some potentially hard to debug errors.
Agreed. Pythonic functions shouldn’t return codes to indicate «success/failure» when one is vastly more likely than the other. Just throw an exception in the exceptional case. That being said, just return a tuple when needed: «return a, b, c»
When failure is common, returning the failure information in a tuple is a good approach. Example would be a function that you call multiple times with test values to find a «good» value, you expect it to fail many times and eventually find a good value. In that case just «return result, reason» rather than raising an exception.
def f(x): # do stuff return (True, modified_string) success, modified_string = f(something)
My partner argue with me about weather should add ( and ) when want to return multi values. When I write code in Pycharm, the ide shows the wornning at lines where return multi values with () , but we can’t find the code style rule at pep8. How do you think about it? Thank you.
Returning a tuple is the usual way to do this in Python.
Throwing an exception for failure is one good way to proceed, and if you’re returning a lot of different values, you can return a tuple. For the specific case you’re citing, I often take an intermediate approach: return the modified string on success, and return None on failure. I’m enough of an unreconstructed C programmer to want to return a NULL pointer to char on failure.
If I were writing a routine to be used as part of a larger library and consumed by other developers, I’d throw an exception on failure. When I’m eating my own dogfood, I’ll probably return different types and test on return.
You can use return statement with multiple expressions
Highly active question. Earn 10 reputation (not counting the association bonus) in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity.
Linked
Related
Hot Network Questions
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.21.43541
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Как вернуть сразу несколько значений из функции в Python 3
Сегодня мы делимся с вами переводом статьи, которую нашли на сайте medium.com. Автор, Vivek Coder, рассказывает о способах возврата значений из функции в Python и объясняет, как можно отличить друг от друга разные структуры данных.
Фото с сайта Unsplash. Автор: Vipul Jha
Python удобен в том числе тем, что позволяет одновременно возвращать из функции сразу несколько значений. Для этого нужно воспользоваться оператором return и вернуть структуру данных с несколькими значениями — например, список общего количества рабочих часов за каждую неделю.
def hours_to_write(happy_hours): week1 = happy_hours + 2 week2 = happy_hours + 4 week3 = happy_hours + 6 return [week1, week2, week3] print(hours_to_write(4)) # [6, 8, 10]
Структуры данных в Python используются для хранения коллекций данных, которые могут быть возвращены посредством оператора return . В этой статье мы рассмотрим способы возврата нескольких значений с помощью подобных структур (словарей, списков и кортежей), а также с помощью классов и классов данных (Python 3.7+).
Способ 1: возврат значений с помощью словарей
Словари содержат комбинации элементов, которые представляют собой пары «ключ — значение» ( key:value ), заключенные в фигурные скобки ( <> ).
Словари, на мой взгляд, это оптимальный вариант для работы, если вы знаете ключ для доступа к значениям. Далее представлен словарь, где ключом является имя человека, а соответствующим значением — возраст.
А теперь перейдем к функции, которая возвращает словарь с парами «ключ — значение».
# A Python program to return multiple values using dictionary # This function returns a dictionary def people_age(): d = dict(); d['Jack'] = 30 d['Kim'] = 28 d['Bob'] = 27 return d d = people_age() print(d) #
Способ 2: возврат значений с помощью списков
Списки похожи на массивы, сформированные с использованием квадратных скобок, однако они могут содержать элементы разных типов. Списки также отличаются от кортежей, поскольку являются изменяемым типом данных. То есть любой список может меняться.
Списки — одна из наиболее универсальных структур данных в Python, потому что им не обязательно сохранять однородность (в них можно включать строки, числа и элементы). Иногда списки даже используют вместе со стеками или очередями.
# A Python program to return multiple values using list def test(): str1 = "Happy" str2 = "Coding" return [str1, str2]; list = test() print(list) # ['Happy', 'Coding']
Вот пример, где возвращается список с натуральными числами.
def natural_numbers(numbers = []): for i in range(1, 16): numbers.append(i) return numbers print(natural_numbers()) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Способ 3: возврат значений с помощью кортежей
Кортежи — это упорядоченные неизменяемые объекты в Python, которые обычно используются для хранения коллекций неоднородных данных.
Кортежи напоминают списки, однако их нельзя изменить после того, как они были объявлены. А еще, как правило, кортежи быстрее в работе, чем списки. Кортеж можно создать, отделив элементы запятыми: x, y, z или (x, y, z) .
На этом примере кортеж используется для хранения данных о сотруднике (имя, опыт работы в годах и название компании).
А вот пример написания функции для возврата кортежа.
# A Python program to return multiple values using tuple # This function returns a tuple def fun(): str1 = "Happy" str2 = "Coding" return str1, str2; # we could also write (str1, str2) str1, str2= fun() print(str1) print(str2) # Happy Coding
Обратите внимание: мы опустили круглые скобки в операторе return , поскольку для возврата кортежа достаточно просто отделить каждый элемент запятой (как показано выше).
Не забывайте, что кортеж можно создать с помощью запятой вместо круглых скобок. Круглые скобки требуются только в тех случаях, когда используются пустые кортежи или вам нужно избежать синтаксической неточности.
Чтобы лучше разобраться в кортежах, обратитесь к официальной документации Python 3 (документация приведена на английском языке. — Прим. ред.).
Ниже показан пример функции, которая использует для возврата кортежа круглые скобки.
def student(name, class): return (name, class) print(student("Brayan", 10)) # ('Brayan', 10)
Повторюсь, кортежи легко перепутать со списками (в конце концов, и те, и другие представляют собой контейнер, состоящий из элементов). Однако нужно помнить о фундаментальном различии: кортежи изменить нельзя, а списки — можно.
Способ 4: возврат значений с помощью объектов
Тут все так же, как в C/C++ или в Java. Можно просто сформировать класс (в C он называется структурой) для сохранения нескольких признаков и возврата объекта класса.
# A Python program to return multiple values using class class Intro: def __init__(self): self.str1 = "hello" self.str2 = "world" # This function returns an object of Intro def message(): return Intro() x = message() print(x.str1) print(x.str2) # hello world
Способ 5: возврат значений с помощью классов данных (Python 3.7+)
Классы данных в Python 3.7+ как раз помогают вернуть класс с автоматически добавленными уникальными методами, модулем typing и другими полезными инструментами.
from dataclasses import dataclass @dataclass class Item_list: name: str perunit_cost: float quantity_available: int = 0 def total_cost(self) -> float: return self.perunit_cost * self.quantity_available book = Item_list("better programming.", 50, 2) x = book.total_cost() print(x) print(book) # 100 Item_list(name='better programming.', perunit_cost=50, quantity_available=2)
Чтобы лучше разобраться в классах данных, обратитесь к официальной документации Python 3 (документация приведена на английском языке. — Прим. ред.).
Вывод
Цель этой статьи — ознакомить вас со способами возврата нескольких значений из функции в Python. И, как вы видите, этих способов действительно много.
Учите матчасть и постоянно развивайте свои навыки программирования. Спасибо за внимание!
Elegant ways to return multiple values from a function
It seems like in most mainstream programming languages, returning multiple values from a function is an extremely awkward thing. The typical solutions are to make either a struct or a plain old data class and return that, or to pass at least some of the parameters by reference or pointer instead of returning them. Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass. The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity. Furthermore, a lot of times there’s one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types. The one language I’m aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking:
a, b = foo(c) # a and b are regular variables. myTuple = foo(c) # myTuple is a tuple of (a, b)
Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you’ve seen in non-mainstream languages are welcome.
14 Answers 14
Pretty much all ML-influenced functional langues (which is most of them) also have great tuple support that makes this sort of thing trivial.
For C++ I like boost::tuple plus boost::tie (or std::tr1 if you have it)
typedef boost::tuple XYZ; XYZ foo(); double x,y,z; boost::tie(x,y,z) = foo();
or a less contrived example
MyMultimap::iterator lower,upper; boost::tie(lower,upper) = some_map.equal_range(key);