Skip to content

Commit 515d7fc

Browse files
author
Kenneth Reitz
committed
Merge pull request realpython#70 from dcrosta/idioms
some idioms I used this morning
2 parents ed439b3 + 8587cf6 commit 515d7fc

File tree

2 files changed

+65
-3
lines changed

2 files changed

+65
-3
lines changed

docs/conf.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525

2626
# Add any Sphinx extension module names here, as strings. They can be extensions
2727
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
28-
extensions = ['sphinx.ext.ifconfig', 'sphinx.ext.todo']
28+
extensions = ['sphinx.ext.ifconfig', 'sphinx.ext.todo', 'sphinx.ext.intersphinx']
2929

3030
# Add any paths that contain templates here, relative to this directory.
3131
templates_path = ['_templates']
@@ -260,3 +260,7 @@
260260
#epub_tocdup = True
261261

262262
todo_include_todos = True
263+
264+
intersphinx_mapping = {
265+
'python': ('http://docs.python.org/', None),
266+
}

docs/writing/style.rst

Lines changed: 60 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,67 @@ Code Style
33

44

55
Idioms
6-
::::::
6+
------
7+
8+
Idiomatic Python code is often referred to as being *Pythonic*.
9+
10+
.. _unpacking-ref:
11+
12+
Unpacking
13+
~~~~~~~~~
14+
15+
If you know the length of a list or tuple, you can assign names to its
16+
elements with unpacking:
17+
18+
.. code-block:: python
19+
20+
for index, item in enumerate(some_list):
21+
# do something with index and item
22+
23+
You can use this to swap variables, as well:
24+
25+
.. code-block:: python
26+
27+
a, b = b, a
28+
29+
Create an ignored variable
30+
~~~~~~~~~~~~~~~~~~~~~~~~~~
31+
32+
If you need to assign something (for instance, in :ref:`unpacking-ref`) but
33+
will not need that variable, use ``_``:
34+
35+
.. code-block:: python
36+
37+
filename = 'foobar.txt'
38+
basename, _, ext = filename.rpartition()
39+
40+
.. note::
41+
42+
"``_``" is commonly used as an alias for the :func:`~gettext.gettext`
43+
function. If your application uses (or may someday use) :mod:`gettext`,
44+
you may want to avoid using ``_`` for ignored variables, as you may
45+
accidentally shadow :func:`~gettext.gettext`.
46+
47+
Create a length-N list of the same thing
48+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
49+
50+
Use the Python list ``*`` operator:
51+
52+
.. code-block:: python
53+
54+
four_nones = [None] * 4
55+
56+
Create a length-N list of lists
57+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
58+
59+
Because lists are mutable, the ``*`` operator (as above) will create a list
60+
of N references to the `same` list, which is not likely what you want.
61+
Instead, use a list comprehension:
62+
63+
.. code-block:: python
64+
65+
four_lists = [[] for _ in xrange(4)]
766
8-
Idiomatic Python code is often referred to as being *pythonic*.
967
1068
1169
Zen of Python

0 commit comments

Comments
 (0)