some idioms I used this morning
authorDan Crosta <dcrosta@late.am>
Tue, 3 Jan 2012 15:03:59 +0000 (10:03 -0500)
committerDan Crosta <dcrosta@late.am>
Wed, 14 Mar 2012 23:09:56 +0000 (16:09 -0700)
docs/writing/style.rst

index 803dca1..ada5d3c 100644 (file)
@@ -3,9 +3,60 @@ Code Style
 
 
 Idioms
-::::::
+------
+
+Idiomatic Python code is often referred to as being *Pythonic*.
+
+.. _unpacking-ref:
+
+Unpacking
+~~~~~~~~~
+
+If you know the length of a list or tuple, you can assign names to its
+elements with unpacking:
+
+.. code-block:: python
+
+    for index, item in enumerate(some_list):
+        # do something with index and item
+
+You can use this to swap variables, as well:
+
+.. code-block:: python
+
+    a, b = b, a
+
+Create an ignored variable
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+If you need to assign something (for instance, in :ref:`unpacking-ref`) but
+will not need that variable, use ``_``:
+
+.. code-block:: python
+
+    filename = 'foobar.txt'
+    basename, _, ext = filename.rpartition()
+
+Create a length-N list of the same thing
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Use the Python list ``*`` operator:
+
+.. code-block:: python
+
+    four_nones = [None] * 4
+
+Create a length-N list of lists
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Because lists are mutable, the ``*`` operator (as above) will create a list
+of N references to the `same` list, which is not likely what you want.
+Instead, use a list comprehension:
+
+.. code-block:: python
+
+    four_lists = [[] for _ in xrange(4)]
 
-Idiomatic Python code is often referred to as being *pythonic*.
 
 
 Zen of Python