@@ -208,6 +208,49 @@ This will guarantee a better separation of duties and easier modifications of
208208existing code, and it will always be possible to publicize a private property ,
209209while privatising a public property might be a much harder operation.
210210
211+ Returning values
212+ ~~~~~~~~~~~~~~~~
213+
214+ Python functions return a value, and you can control this return value with the
215+ return statement for all of them but the object constructor `__init__ ()` and the
216+ special case of generators.
217+
218+ When a function grows in complexity is not uncommon to use multiple return statements
219+ inside the function' s body. However, in order to keep a clear intent and a sustainable
220+ readability level, it is preferable to avoid returning meaningful values from many
221+ output point in the body.
222+
223+ There are two main cases for returning values in a function: The result of the function
224+ return when it has been processed normally, and the error cases that indicate a wrong
225+ input paramter or any other reason for the function to not be able to complete its
226+ computation or task.
227+
228+ If you do not wish to raise exceptions for the second case, then returning a value, such
229+ as None or False , indicating that the function could not perform correctly might be needed. In this
230+ case, it is better to return as early as the incorrect context has been detected. It will
231+ help to flatten the structure of the function: all the code after the return - because- of- error
232+ statement can assume the condition is met to further compute the function' s main result.
233+ Having multiple such return statement is often necessary.
234+
235+ However, when a function has multiple main exit points for its normal course, it becomes
236+ difficult to debug the returned result, and it may be preferable to keep a single exit
237+ point. This will also help factoring out some code paths, and the multiple exit point
238+ is a probable indication that such a refactoring is needed.
239+
240+ .. code- block:: python
241+
242+ def complex_function(a, b, c):
243+ if not a:
244+ return None # Raising an exception might be better
245+ if not b:
246+ return None # Raising an exception might be better
247+ # Some complex code trying to compute x from a, b and c
248+ # Resist temptation to return x if succeeded
249+ if not x:
250+ # Some Plan-B computation of x
251+ return x # One single exit point for the returned value x will help
252+ # when maintaining the code.
253+
211254Idioms
212255------
213256
@@ -232,6 +275,12 @@ You can use this to swap variables, as well:
232275
233276 a, b = b, a
234277
278+ Nested unpacking works too:
279+
280+ .. code- block:: python
281+
282+ a, (b, c) = 1 , (2 , 3 )
283+
235284Create an ignored variable
236285~~~~~~~~~~~~~~~~~~~~~~~~~~
237286
0 commit comments