|
| 1 | +Not using named tuples when returning more than one value from a function |
| 2 | +========================================================================= |
| 3 | + |
| 4 | +Summary |
| 5 | +------- |
| 6 | + |
| 7 | +Use named tuples when returning more than one value from a function. This makes code easier to read and makes the data easier to access, as each value can be accessed via a name in addition to an index. |
| 8 | + |
| 9 | +Description |
| 10 | +----------- |
| 11 | + |
| 12 | +Named tuples can be used anywhere where normal tuples are acceptable, but their values can be accessed through their name in addition to their index, which makes code more verbose and easier to read. |
| 13 | + |
| 14 | +Examples |
| 15 | +---------- |
| 16 | + |
| 17 | +Using normal tuple to return multiple values |
| 18 | +............................................ |
| 19 | + |
| 20 | +The module below returns a first name, middle name, and last name using a normal, unnamed tuple. After calling the tuple, each value can only be returned via an index. This code is difficult to use: the caller of the function has to know that the first element is the first name, the second is the middle name, and the third is the last name. |
| 21 | + |
| 22 | +.. warning:: The code below is an example of an error. Using this code will create bugs in your programs! |
| 23 | + |
| 24 | +.. code:: python |
| 25 | +
|
| 26 | + def get_name(): |
| 27 | + return "Richard", "Xavier", "Jones" |
| 28 | +
|
| 29 | + name = get_name() |
| 30 | +
|
| 31 | + print name[0], name[1], name[2] # ('Richard', 'Xavier', 'Jones') # hard to read |
| 32 | +
|
| 33 | +Solutions |
| 34 | +--------- |
| 35 | + |
| 36 | +Use named tuples to return multiple values |
| 37 | +.......................................... |
| 38 | + |
| 39 | +The modified module below uses named tuples to return multiple values. This code is easier to use and easier to read, as now the caller can access each piece of data via a straightforward name (like ``name.first``). |
| 40 | + |
| 41 | +.. code:: python |
| 42 | +
|
| 43 | + from collections import namedtuple |
| 44 | +
|
| 45 | + def get_name(): |
| 46 | + name = namedtuple("name", ["first", "middle", "last"]) |
| 47 | + return name("Richard", "Xavier", "Jones") |
| 48 | +
|
| 49 | + name = get_name() |
| 50 | +
|
| 51 | + print name.first, name.middle, name.last # much easier to read |
| 52 | +
|
| 53 | +References |
| 54 | +---------- |
| 55 | +- `Python Standard Libary - collections.namedtuple <https://docs.python.org/2/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields>`_ |
0 commit comments