Named tuples were added in 2.6 for this purpose. Also see os.stat for a similar builtin example.
>>> import collections
>>> Point = collections.namedtuple('Point', ['x', 'y'])
>>> p = Point(1, y=2)
>>> p.x, p.y
1 2
>>> p[0], p[1]
1 2
In recent versions of Python 3 (3.6+, I think), the new typing library got the NamedTuple class to make named tuples easier to create and more powerful. Inheriting from typing.NamedTuple lets you use docstrings, default values, and type annotations.
Example (From the docs):
class Employee(NamedTuple): # inherit from typing.NamedTuple
name: str
id: int = 3 # default value
employee = Employee('Guido')
assert employee.id == 3
Answer from A. Coady on Stack OverflowVideos
Named tuples were added in 2.6 for this purpose. Also see os.stat for a similar builtin example.
>>> import collections
>>> Point = collections.namedtuple('Point', ['x', 'y'])
>>> p = Point(1, y=2)
>>> p.x, p.y
1 2
>>> p[0], p[1]
1 2
In recent versions of Python 3 (3.6+, I think), the new typing library got the NamedTuple class to make named tuples easier to create and more powerful. Inheriting from typing.NamedTuple lets you use docstrings, default values, and type annotations.
Example (From the docs):
class Employee(NamedTuple): # inherit from typing.NamedTuple
name: str
id: int = 3 # default value
employee = Employee('Guido')
assert employee.id == 3
For small projects I find it easiest to work with tuples. When that gets too hard to manage (and not before) I start grouping things into logical structures, however I think your suggested use of dictionaries and ReturnValue objects is wrong (or too simplistic).
Returning a dictionary with keys "y0", "y1", "y2", etc. doesn't offer any advantage over tuples. Returning a ReturnValue instance with properties .y0, .y1, .y2, etc. doesn't offer any advantage over tuples either. You need to start naming things if you want to get anywhere, and you can do that using tuples anyway:
def get_image_data(filename):
[snip]
return size, (format, version, compression), (width,height)
size, type, dimensions = get_image_data(x)
IMHO, the only good technique beyond tuples is to return real objects with proper methods and properties, like you get from re.match() or open(file).
Hello developers, I want to know about how can I return multiple values from a function. I have read few articles but still confused.
You cannot return two values, but you can return a tuple or a list and unpack it after the call:
Copydef select_choice():
...
return i, card # or [i, card]
my_i, my_card = select_choice()
On line return i, card i, card means creating a tuple. You can also use parenthesis like return (i, card), but tuples are created by comma, so parens are not mandatory. But you can use parens to make your code more readable or to split the tuple over multiple lines. The same applies to line my_i, my_card = select_choice().
If you want to return more than two values, consider using a named tuple. It will allow the caller of the function to access fields of the returned value by name, which is more readable. You can still access items of the tuple by index. For example in Schema.loads method Marshmallow framework returns a UnmarshalResult which is a namedtuple. So you can do:
Copydata, errors = MySchema.loads(request.json())
if errors:
...
or
Copyresult = MySchema.loads(request.json())
if result.errors:
...
else:
# use `result.data`
In other cases you may want to return a dict from your function:
Copydef select_choice():
...
return {'i': i, 'card': card, 'other_field': other_field, ...}
But consider returning an instance of a utility class (or a Pydantic/dataclass model instance), which wraps your data:
Copyclass ChoiceData(pydantic.BaseModel):
i: int
card: str
other_field: typing.Any
def select_choice():
...
return ChoiceData(i=i, card=card, other_field=other_field)
choice_data = select_choice()
print(choice_data.i, choice_data.card)
I would like to return two values from a function in two separate variables.
What would you expect it to look like on the calling end? You can't write a = select_choice(); b = select_choice() because that would call the function twice.
Values aren't returned "in variables"; that's not how Python works. A function returns values (objects). A variable is just a name for a value in a given context. When you call a function and assign the return value somewhere, what you're doing is giving the received value a name in the calling context. The function doesn't put the value "into a variable" for you, the assignment does (never mind that the variable isn't "storage" for the value, but again, just a name).
When i tried to to use
return i, card, it returns atupleand this is not what i want.
Actually, it's exactly what you want. All you have to do is take the tuple apart again.
And i want to be able to use these values separately.
So just grab the values out of the tuple.
The easiest way to do this is by unpacking:
Copya, b = select_choice()
EDIT: Since Python 3.9 and the acceptance of PEP 585, you should use the built-in tuple class to typehint tuples.
You can use a typing.Tuple type hint (to specify the type of the content of the tuple, if it is not necessary, the built-in class tuple can be used instead):
from typing import Tuple, List
def greeting(name: str) -> Tuple[str, List[float], int]:
# do something
return a, b, c
Multiple return values in python are returned as a tuple, and the type hint for a tuple is not the tuple class, but typing.Tuple.
import typing
def greeting(name: str) -> typing.Tuple[str, List[float], int]:
# do something
return a,b,c