Skip to content

Commit 4969f16

Browse files
committed
improved the multi return values section. Closes yasoob#90
1 parent d53b7b5 commit 4969f16

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

global_&_return.rst

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,4 +125,36 @@ Or by more common convention:
125125
print(profile_age)
126126
# Output: 30
127127
128+
Keep in mind that even in the above example we are returning a tuple (despite the lack of paranthesis) and not separate multiple values. If you want to take it one step further, you can also make use of `namedtuple <https://docs.python.org/3/library/collections.html#collections.namedtuple>`_. Here is an example:
129+
130+
.. code:: python
131+
132+
from collections import namedtuple
133+
def profile():
134+
Person = namedtuple('Person', 'name age')
135+
return Person(name="Danny", age=31)
136+
137+
# Use as namedtuple
138+
p = profile()
139+
print(p, type(p))
140+
# Person(name='Danny', age=31) <class '__main__.Person'>
141+
print(p.name)
142+
# Danny
143+
print(p.age)
144+
#31
145+
146+
# Use as plain tuple
147+
p = profile()
148+
print(p[0])
149+
# Danny
150+
print(p[1])
151+
#31
152+
153+
# Unpack it immediatly
154+
name, age = profile()
155+
print(name)
156+
# Danny
157+
print(age)
158+
#31
159+
128160
This is a better way to do it along with returning ``lists`` and ``dicts``. Don't use ``global`` keyword unless you know what you are doing. ``global`` might be a better option in a few cases but is not in most of them.

0 commit comments

Comments
 (0)