mirror of
https://github.com/kennethreitz/python-guide.git
synced 2026-06-05 23:00:18 +00:00
Merge pull request #297 from kuyan/master
Formatting, code highlighting fixes.
This commit is contained in:
+8
-6
@@ -16,8 +16,8 @@ Vim is a text editor which uses keyboard shortcuts for editing instead of menus
|
|||||||
or icons. There exist a couple of plugins and settings for the VIM editor to
|
or icons. There exist a couple of plugins and settings for the VIM editor to
|
||||||
aid Python development. If you only develop in Python, a good start is to set
|
aid Python development. If you only develop in Python, a good start is to set
|
||||||
the default settings for indentation and line-wrapping to values compliant with
|
the default settings for indentation and line-wrapping to values compliant with
|
||||||
`PEP 8 <http://www.python.org/dev/peps/pep-0008/>`_. In your home directory,
|
:pep:`8`. In your home directory, open a file called `.vimrc` and add the
|
||||||
open a file called `.vimrc` and add the following lines:::
|
following lines:::
|
||||||
|
|
||||||
set textwidth=79 " lines longer than 79 columns will be broken
|
set textwidth=79 " lines longer than 79 columns will be broken
|
||||||
set shiftwidth=4 " operation >> indents 4 columns; << unindents 4 columns
|
set shiftwidth=4 " operation >> indents 4 columns; << unindents 4 columns
|
||||||
@@ -113,12 +113,14 @@ scripters and novice users alike."
|
|||||||
Sublime Text
|
Sublime Text
|
||||||
------------
|
------------
|
||||||
|
|
||||||
"`Sublime Text <http://www.sublimetext.com/>`_ is a sophisticated text editor
|
`Sublime Text <http://www.sublimetext.com/>`_ is a sophisticated text
|
||||||
for code, html and prose. You'll love the slick user interface and
|
editor for code, markup and prose. You'll love the slick user interface,
|
||||||
extraordinary features."
|
extraordinary features and amazing performance.
|
||||||
|
|
||||||
Sublime Text has excellent support for editing Python code and uses Python for
|
Sublime Text has excellent support for editing Python code and uses Python for
|
||||||
its plugin API.
|
its plugin API. It also has plugins a diverse variety of plugins, `some of which <https://github.com/SublimeLinter/SublimeLinter>`_
|
||||||
|
allow for in-editor PEP8 checking and code "linting".
|
||||||
|
|
||||||
|
|
||||||
IDEs
|
IDEs
|
||||||
::::
|
::::
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ PEPs
|
|||||||
PEPs are *Python Enhancement Proposals*. They describe changes to Python itself,
|
PEPs are *Python Enhancement Proposals*. They describe changes to Python itself,
|
||||||
or the standards around it.
|
or the standards around it.
|
||||||
|
|
||||||
There are three different types of PEPs (as defined by `PEP1 <http://www.python.org/dev/peps/pep-0001/>`_):
|
There are three different types of PEPs (as defined by :pep:`1`):
|
||||||
|
|
||||||
**Standards**
|
**Standards**
|
||||||
Describes a new feature or implementation.
|
Describes a new feature or implementation.
|
||||||
@@ -45,13 +45,13 @@ Notable PEPs
|
|||||||
|
|
||||||
There are a few PEPs that could be considered required reading:
|
There are a few PEPs that could be considered required reading:
|
||||||
|
|
||||||
- `PEP8 <http://www.python.org/dev/peps/pep-0008/>`_: The Python Style Guide.
|
- :pep:`8`: The Python Style Guide.
|
||||||
Read this. All of it. Follow it.
|
Read this. All of it. Follow it.
|
||||||
|
|
||||||
- `PEP20 <http://www.python.org/dev/peps/pep-0020/>`_: The Zen of Python.
|
- :pep:`20`: The Zen of Python.
|
||||||
A list of 19 statements that briefly explain the philosophy behind Python.
|
A list of 19 statements that briefly explain the philosophy behind Python.
|
||||||
|
|
||||||
- `PEP257 <http://www.python.org/dev/peps/pep-0257/>`_: Docstring Conventions.
|
- :pep:`257`: Docstring Conventions.
|
||||||
Gives guidelines for semantics and conventions associated with Python
|
Gives guidelines for semantics and conventions associated with Python
|
||||||
docstrings.
|
docstrings.
|
||||||
|
|
||||||
|
|||||||
@@ -82,7 +82,6 @@ whether they're an old hand or a first-time Pythonista, and the authors to
|
|||||||
the Guide will gladly help if you have any questions about the
|
the Guide will gladly help if you have any questions about the
|
||||||
appropriateness, completeness, or accuracy of a contribution.
|
appropriateness, completeness, or accuracy of a contribution.
|
||||||
|
|
||||||
To get started working on The Hitchhiker's Guide, see
|
To get started working on The Hitchhiker's Guide, see the :doc:`/notes/contribute` page.
|
||||||
the: doc:`/notes/contribute` page.
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ Python Koans
|
|||||||
|
|
||||||
Python Koans is a port of Edgecase's Ruby Koans. It uses a test-driven
|
Python Koans is a port of Edgecase's Ruby Koans. It uses a test-driven
|
||||||
approach, q.v. TEST DRIVEN DESIGN SECTION to provide an interactive tutorial
|
approach, q.v. TEST DRIVEN DESIGN SECTION to provide an interactive tutorial
|
||||||
teaching basic python concepts. By fixing assertion statements that fail in a
|
teaching basic python concepts. By fixing assertion statements that fail in a
|
||||||
test script, this provides sequential steps to learning python.
|
test script, this provides sequential steps to learning python.
|
||||||
|
|
||||||
For those used to languages and figuring out puzzles on their own, this can be
|
For those used to languages and figuring out puzzles on their own, this can be
|
||||||
@@ -105,7 +105,7 @@ is focused on the more advanced crowd.
|
|||||||
|
|
||||||
It starts with topics like decorators (with caching, proxy, and context manager
|
It starts with topics like decorators (with caching, proxy, and context manager
|
||||||
case-studies), method resolution order, using super() and meta-programming, and
|
case-studies), method resolution order, using super() and meta-programming, and
|
||||||
general PEP8 best practices.
|
general :pep:`8` best practices.
|
||||||
|
|
||||||
It has a detailed, multi-chapter case study on writing and releasing a package
|
It has a detailed, multi-chapter case study on writing and releasing a package
|
||||||
and eventually an application, including a chapter on using zc.buildout. Later
|
and eventually an application, including a chapter on using zc.buildout. Later
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
|
=======
|
||||||
License
|
License
|
||||||
-------
|
=======
|
||||||
|
|
||||||
.. todo:: Determine License
|
The Guide is licensed under the `Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported license <https://creativecommons.org/licenses/by-nc-sa/3.0/>`_.
|
||||||
+40
-16
@@ -39,24 +39,32 @@ Headings
|
|||||||
|
|
||||||
Use the following styles for headings.
|
Use the following styles for headings.
|
||||||
|
|
||||||
Chapter title::
|
Chapter title:
|
||||||
|
|
||||||
|
.. code-block:: rest
|
||||||
|
|
||||||
#########
|
#########
|
||||||
Chapter 1
|
Chapter 1
|
||||||
#########
|
#########
|
||||||
|
|
||||||
Page title::
|
Page title:
|
||||||
|
|
||||||
|
.. code-block:: rest
|
||||||
|
|
||||||
===================
|
===================
|
||||||
Time is an Illusion
|
Time is an Illusion
|
||||||
===================
|
===================
|
||||||
|
|
||||||
Section headings::
|
Section headings:
|
||||||
|
|
||||||
|
.. code-block:: rest
|
||||||
|
|
||||||
Lunchtime Doubly So
|
Lunchtime Doubly So
|
||||||
-------------------
|
-------------------
|
||||||
|
|
||||||
Sub section headings::
|
Sub section headings:
|
||||||
|
|
||||||
|
.. code-block:: rest
|
||||||
|
|
||||||
Very Deep
|
Very Deep
|
||||||
~~~~~~~~~
|
~~~~~~~~~
|
||||||
@@ -74,7 +82,9 @@ Code Examples
|
|||||||
|
|
||||||
Wrap all code examples at 70 characters to avoid horizontal scrollbars.
|
Wrap all code examples at 70 characters to avoid horizontal scrollbars.
|
||||||
|
|
||||||
Command line examples::
|
Command line examples:
|
||||||
|
|
||||||
|
.. code-block:: rest
|
||||||
|
|
||||||
.. code-block:: console
|
.. code-block:: console
|
||||||
|
|
||||||
@@ -83,7 +93,9 @@ Command line examples::
|
|||||||
|
|
||||||
Be sure to include the ``$`` prefix before each line.
|
Be sure to include the ``$`` prefix before each line.
|
||||||
|
|
||||||
Python interpreter examples::
|
Python interpreter examples:
|
||||||
|
|
||||||
|
.. code-block:: rest
|
||||||
|
|
||||||
Label the example::
|
Label the example::
|
||||||
|
|
||||||
@@ -91,7 +103,9 @@ Python interpreter examples::
|
|||||||
|
|
||||||
>>> import this
|
>>> import this
|
||||||
|
|
||||||
Python examples::
|
Python examples:
|
||||||
|
|
||||||
|
.. code-block:: rest
|
||||||
|
|
||||||
Descriptive title::
|
Descriptive title::
|
||||||
|
|
||||||
@@ -103,16 +117,20 @@ Python examples::
|
|||||||
Externally Linking
|
Externally Linking
|
||||||
------------------
|
------------------
|
||||||
|
|
||||||
* Prefer labels for well known subjects (ex: proper nouns) when linking::
|
* Prefer labels for well known subjects (ex: proper nouns) when linking:
|
||||||
|
|
||||||
Sphinx_ is used to document Python.
|
.. code-block:: rest
|
||||||
|
|
||||||
.. _Sphinx: http://sphinx.pocoo.org
|
Sphinx_ is used to document Python.
|
||||||
|
|
||||||
|
.. _Sphinx: http://sphinx.pocoo.org
|
||||||
|
|
||||||
* Prefer to use descriptive labels with inline links instead of leaving bare
|
* Prefer to use descriptive labels with inline links instead of leaving bare
|
||||||
links::
|
links:
|
||||||
|
|
||||||
Read the `Sphinx Tutorial <http://sphinx.pocoo.org/tutorial.html>`_
|
.. code-block:: rest
|
||||||
|
|
||||||
|
Read the `Sphinx Tutorial <http://sphinx.pocoo.org/tutorial.html>`_
|
||||||
|
|
||||||
* Avoid using labels such as "click here", "this", etc. preferring
|
* Avoid using labels such as "click here", "this", etc. preferring
|
||||||
descriptive labels (SEO worthy) instead.
|
descriptive labels (SEO worthy) instead.
|
||||||
@@ -124,7 +142,9 @@ To cross-reference other parts of this documentation, use the `:ref:
|
|||||||
<http://sphinx.pocoo.org/markup/inline.html#cross-referencing-arbitrary-locations>`_
|
<http://sphinx.pocoo.org/markup/inline.html#cross-referencing-arbitrary-locations>`_
|
||||||
keyword and labels.
|
keyword and labels.
|
||||||
|
|
||||||
To make reference labels more clear and unique, always add a ``-ref`` suffix::
|
To make reference labels more clear and unique, always add a ``-ref`` suffix:
|
||||||
|
|
||||||
|
.. code-block:: rest
|
||||||
|
|
||||||
.. _some-section-ref:
|
.. _some-section-ref:
|
||||||
|
|
||||||
@@ -137,14 +157,18 @@ Notes and Warnings
|
|||||||
Make use of the appropriate `admonitions directives
|
Make use of the appropriate `admonitions directives
|
||||||
<http://sphinx.pocoo.org/rest.html#directives>`_ when making notes.
|
<http://sphinx.pocoo.org/rest.html#directives>`_ when making notes.
|
||||||
|
|
||||||
Notes::
|
Notes:
|
||||||
|
|
||||||
|
.. code-block:: rest
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
The Hitchhiker’s Guide to the Galaxy has a few things to say
|
The Hitchhiker’s Guide to the Galaxy has a few things to say
|
||||||
on the subject of towels. A towel, it says, is about the most
|
on the subject of towels. A towel, it says, is about the most
|
||||||
massively useful thing an interstellar hitch hiker can have.
|
massively useful thing an interstellar hitch hiker can have.
|
||||||
|
|
||||||
Warnings::
|
Warnings:
|
||||||
|
|
||||||
|
.. code-block:: rest
|
||||||
|
|
||||||
.. warning:: DON'T PANIC
|
.. warning:: DON'T PANIC
|
||||||
|
|
||||||
@@ -156,7 +180,7 @@ Please mark any incomplete areas of The Guide with a `todo directive
|
|||||||
avoid cluttering the :ref:`todo-list-ref`, use a single ``todo`` for stub
|
avoid cluttering the :ref:`todo-list-ref`, use a single ``todo`` for stub
|
||||||
documents or large incomplete sections.
|
documents or large incomplete sections.
|
||||||
|
|
||||||
::
|
.. code-block:: rest
|
||||||
|
|
||||||
.. todo::
|
.. todo::
|
||||||
Learn the Ultimate Answer to the Ultimate Question
|
Learn the Ultimate Answer to the Ultimate Question
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ DB-API
|
|||||||
------
|
------
|
||||||
|
|
||||||
The Python Database API (DB-API) defines a standard interface for Python
|
The Python Database API (DB-API) defines a standard interface for Python
|
||||||
database access modules. It's documented in `PEP 249 <http://www.python.org/dev/peps/pep-0249/>`_.
|
database access modules. It's documented in :pep:`249`.
|
||||||
Nearly all Python database modules such as `sqlite3`, `psycopg` and
|
Nearly all Python database modules such as `sqlite3`, `psycopg` and
|
||||||
`mysql-python` conform to this interface.
|
`mysql-python` conform to this interface.
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ The `Python Imaging Library <http://www.pythonware.com/products/pil/>`_, or PIL
|
|||||||
for short, is *the* library for image manipulation in Python. Unfortunately, its
|
for short, is *the* library for image manipulation in Python. Unfortunately, its
|
||||||
development has stagnated, with its last release in 2009.
|
development has stagnated, with its last release in 2009.
|
||||||
|
|
||||||
Lucky for you, there's an actively-developed fork of PIL called `Pillow <http://python-imaging.github.io/>`_ -
|
Luckily for you, there's an actively-developed fork of PIL called `Pillow <http://python-imaging.github.io/>`_ -
|
||||||
it's easier to install, runs on all operating systems, and supports Python 3.
|
it's easier to install, runs on all operating systems, and supports Python 3.
|
||||||
|
|
||||||
Installation
|
Installation
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ interface between web servers and Python web application frameworks. By
|
|||||||
standardizing behavior and communication between web servers and Python web
|
standardizing behavior and communication between web servers and Python web
|
||||||
frameworks, WSGI makes it possible to write portable Python web code that
|
frameworks, WSGI makes it possible to write portable Python web code that
|
||||||
can be deployed in any :ref:`WSGI-compliant web server <wsgi-servers-ref>`.
|
can be deployed in any :ref:`WSGI-compliant web server <wsgi-servers-ref>`.
|
||||||
WSGI is documented in `PEP-3333 <http://www.python.org/dev/peps/pep-3333/>`_.
|
WSGI is documented in :pep:`3333`.
|
||||||
|
|
||||||
|
|
||||||
Frameworks
|
Frameworks
|
||||||
|
|||||||
@@ -104,9 +104,7 @@ In Python, *docstrings* describe modules, classes, and functions: ::
|
|||||||
"""Returns the square root of self times self."""
|
"""Returns the square root of self times self."""
|
||||||
...
|
...
|
||||||
|
|
||||||
In general, follow the `comment section of PEP 0008`_ (the "Python Style Guide").
|
In general, follow the comment section of :pep:`8#comments` (the "Python Style Guide").
|
||||||
|
|
||||||
.. _comment section of PEP 0008: http://www.python.org/dev/peps/pep-0008/#comments
|
|
||||||
|
|
||||||
Commenting Sections of Code
|
Commenting Sections of Code
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
@@ -137,9 +135,7 @@ operation of the function or class: ::
|
|||||||
"""Returns the square root of self times self."""
|
"""Returns the square root of self times self."""
|
||||||
...
|
...
|
||||||
|
|
||||||
.. seealso:: Further reading on docstrings: `PEP 0257`_
|
.. seealso:: Further reading on docstrings: :pep:`257`
|
||||||
|
|
||||||
.. _PEP 0257: http://www.python.org/dev/peps/pep-0257/
|
|
||||||
|
|
||||||
|
|
||||||
Other Tools
|
Other Tools
|
||||||
|
|||||||
+11
-12
@@ -35,9 +35,9 @@ include:
|
|||||||
|
|
||||||
- Multiple and messy circular dependencies: if your classes
|
- Multiple and messy circular dependencies: if your classes
|
||||||
Table and Chair in furn.py need to import Carpenter from workers.py
|
Table and Chair in furn.py need to import Carpenter from workers.py
|
||||||
to answer a question such as table.isdoneby(),
|
to answer a question such as ``table.isdoneby()``,
|
||||||
and if conversely the class Carpenter needs to import Table and Chair,
|
and if conversely the class Carpenter needs to import Table and Chair,
|
||||||
to answer the question carpenter.whatdo(), then you
|
to answer the question ``carpenter.whatdo()``, then you
|
||||||
have a circular dependency. In this case you will have to resort to
|
have a circular dependency. In this case you will have to resort to
|
||||||
fragile hacks such as using import statements inside
|
fragile hacks such as using import statements inside
|
||||||
methods or functions.
|
methods or functions.
|
||||||
@@ -236,7 +236,7 @@ processes are spawned to respond to external requests that can
|
|||||||
happen at the same time. In this case, holding some state into instantiated
|
happen at the same time. In this case, holding some state into instantiated
|
||||||
objects, which means keeping some static information about the world, is prone
|
objects, which means keeping some static information about the world, is prone
|
||||||
to concurrency problems or race-conditions. Sometimes, between the initialization of
|
to concurrency problems or race-conditions. Sometimes, between the initialization of
|
||||||
the state of an object (usually done with the __init__() method) and the actual use
|
the state of an object (usually done with the ``__init__()`` method) and the actual use
|
||||||
of the object state through one of its methods, the world may have changed, and
|
of the object state through one of its methods, the world may have changed, and
|
||||||
the retained state may be outdated. For example, a request may load an item in
|
the retained state may be outdated. For example, a request may load an item in
|
||||||
memory and mark it as read by a user. If another request requires the deletion
|
memory and mark it as read by a user. If another request requires the deletion
|
||||||
@@ -383,7 +383,7 @@ Python has two kinds of built-in or user-defined types.
|
|||||||
|
|
||||||
Mutable types are those that allow in-place modification
|
Mutable types are those that allow in-place modification
|
||||||
of the content. Typical mutables are lists and dictionaries:
|
of the content. Typical mutables are lists and dictionaries:
|
||||||
All lists have mutating methods, like append() or pop(), and
|
All lists have mutating methods, like ``append()`` or ``pop()``, and
|
||||||
can be modified in place. The same goes for dictionaries.
|
can be modified in place. The same goes for dictionaries.
|
||||||
|
|
||||||
Immutable types provide no method for changing their content.
|
Immutable types provide no method for changing their content.
|
||||||
@@ -418,7 +418,7 @@ its parts, it is much more efficient to accumulate the parts in a list,
|
|||||||
which is mutable, and then glue ('join') the parts together when the
|
which is mutable, and then glue ('join') the parts together when the
|
||||||
full string is needed. One thing to notice, however, is that list
|
full string is needed. One thing to notice, however, is that list
|
||||||
comprehensions are better and faster than constructing a list in a loop
|
comprehensions are better and faster than constructing a list in a loop
|
||||||
with calls to append().
|
with calls to ``append()``.
|
||||||
|
|
||||||
**Bad**
|
**Bad**
|
||||||
|
|
||||||
@@ -448,10 +448,10 @@ with calls to append().
|
|||||||
nums = [str(n) for n in range(20)]
|
nums = [str(n) for n in range(20)]
|
||||||
print "".join(nums)
|
print "".join(nums)
|
||||||
|
|
||||||
One final thing to mention about strings is that using join() is not always
|
One final thing to mention about strings is that using ``join()`` is not always
|
||||||
best. In the instances where you are creating a new string from a pre-determined
|
best. In the instances where you are creating a new string from a pre-determined
|
||||||
number of strings, using the addition operator is actually faster, but in cases
|
number of strings, using the addition operator is actually faster, but in cases
|
||||||
like above or in cases where you are adding to an existing string, using join()
|
like above or in cases where you are adding to an existing string, using ``join()``
|
||||||
should be your preferred method.
|
should be your preferred method.
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
@@ -464,11 +464,10 @@ should be your preferred method.
|
|||||||
foo = ''.join([foo, 'ooo'])
|
foo = ''.join([foo, 'ooo'])
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
You can also use the **%** formatting operator to concatenate the
|
You can also use the ``%`` formatting operator to concatenate the
|
||||||
pre-determined number of strings besides **join()** and **+**. However,
|
pre-determined number of strings besides ``join()`` and ``+``. However,
|
||||||
according to `PEP 3101 <http://www.python.org/dev/peps/pep-3101/>`_,
|
according to :pep:`3101`, the ``%`` operator became deprecated in
|
||||||
**%** operator became deprecated in Python 3.1 and will be replaced by the
|
Python 3.1 and will be replaced by the ``format()`` method in the later versions.
|
||||||
**format()** method in the later versions.
|
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
|
|||||||
+8
-10
@@ -117,8 +117,8 @@ follow the syntax that is the closest to the function definition: ``send('Hello'
|
|||||||
'World', cc='Cthulhu', bcc='God')``.
|
'World', cc='Cthulhu', bcc='God')``.
|
||||||
|
|
||||||
As a side note, following `YAGNI <http://en.wikipedia.org/wiki/You_ain't_gonna_need_it>`_
|
As a side note, following `YAGNI <http://en.wikipedia.org/wiki/You_ain't_gonna_need_it>`_
|
||||||
principle, it is often harder to remove an optional argument (and its logic inside the
|
principle, it is often harder to remove an optional argument (and its logic inside the
|
||||||
function) that was added "just in case" and is seemingly never used, than to add a
|
function) that was added "just in case" and is seemingly never used, than to add a
|
||||||
new optional argument and its logic when needed.
|
new optional argument and its logic when needed.
|
||||||
|
|
||||||
3. The **arbitrary argument list** is the third way to pass arguments to a
|
3. The **arbitrary argument list** is the third way to pass arguments to a
|
||||||
@@ -256,14 +256,14 @@ are a probable indication that such a refactoring is needed.
|
|||||||
Idioms
|
Idioms
|
||||||
------
|
------
|
||||||
|
|
||||||
A programming idiom, put simply, is a *way* to write code. The notion of programming idioms
|
A programming idiom, put simply, is a *way* to write code. The notion of programming idioms
|
||||||
is discussed amply at `c2 <http://c2.com/cgi/wiki?ProgrammingIdiom>`_ and at `Stack Overflow <http://stackoverflow.com/questions/302459/what-is-a-programming-idiom>`_.
|
is discussed amply at `c2 <http://c2.com/cgi/wiki?ProgrammingIdiom>`_ and at `Stack Overflow <http://stackoverflow.com/questions/302459/what-is-a-programming-idiom>`_.
|
||||||
|
|
||||||
Idiomatic Python code is often referred to as being *Pythonic*.
|
Idiomatic Python code is often referred to as being *Pythonic*.
|
||||||
|
|
||||||
Although there usually is one-- and preferably only one --obvious way to do it;
|
Although there usually is one-- and preferably only one --obvious way to do it;
|
||||||
*the* way to write idiomatic Python code can be non-obvious to Python beginners. So,
|
*the* way to write idiomatic Python code can be non-obvious to Python beginners. So,
|
||||||
good idioms must be consciously acquired.
|
good idioms must be consciously acquired.
|
||||||
|
|
||||||
Some common Python idioms follow:
|
Some common Python idioms follow:
|
||||||
|
|
||||||
@@ -362,7 +362,7 @@ For more information see this `StackOverflow <http://stackoverflow.com/questions
|
|||||||
Zen of Python
|
Zen of Python
|
||||||
-------------
|
-------------
|
||||||
|
|
||||||
Also known as PEP 20, the guiding principles for Python's design.
|
Also known as :pep:`20`, the guiding principles for Python's design.
|
||||||
|
|
||||||
::
|
::
|
||||||
|
|
||||||
@@ -397,9 +397,7 @@ slides from a Python user group
|
|||||||
PEP 8
|
PEP 8
|
||||||
-----
|
-----
|
||||||
|
|
||||||
PEP 8 is the de-facto code style guide for Python.
|
:pep:`8` is the de-facto code style guide for Python.
|
||||||
|
|
||||||
`PEP 8 <http://www.python.org/dev/peps/pep-0008/>`_
|
|
||||||
|
|
||||||
Conforming your Python code to PEP 8 is generally a good idea and helps make
|
Conforming your Python code to PEP 8 is generally a good idea and helps make
|
||||||
code more consistent when working on projects with other developers. There
|
code more consistent when working on projects with other developers. There
|
||||||
|
|||||||
+13
-13
@@ -16,7 +16,7 @@ Some general rules of testing:
|
|||||||
alone, and also within the test suite, regardless of the order they are called.
|
alone, and also within the test suite, regardless of the order they are called.
|
||||||
The implication of this rule is that each test must be loaded with a fresh
|
The implication of this rule is that each test must be loaded with a fresh
|
||||||
dataset and may have to do some cleanup afterwards. This is usually
|
dataset and may have to do some cleanup afterwards. This is usually
|
||||||
handled by setUp() and tearDown() methods.
|
handled by `setUp()` and `tearDown()` methods.
|
||||||
|
|
||||||
- Try hard to make tests that run fast. If one single test needs more than a
|
- Try hard to make tests that run fast. If one single test needs more than a
|
||||||
few millisecond to run, development will be slowed down or the tests will not
|
few millisecond to run, development will be slowed down or the tests will not
|
||||||
@@ -112,7 +112,7 @@ test suite runs.
|
|||||||
|
|
||||||
A simple doctest in a function:
|
A simple doctest in a function:
|
||||||
|
|
||||||
::
|
.. code-block:: python
|
||||||
|
|
||||||
def square(x):
|
def square(x):
|
||||||
"""Squares x.
|
"""Squares x.
|
||||||
@@ -142,7 +142,7 @@ py.test
|
|||||||
|
|
||||||
py.test is a no-boilerplate alternative to Python's standard unittest module.
|
py.test is a no-boilerplate alternative to Python's standard unittest module.
|
||||||
|
|
||||||
::
|
.. code-block:: console
|
||||||
|
|
||||||
$ pip install pytest
|
$ pip install pytest
|
||||||
|
|
||||||
@@ -150,7 +150,7 @@ Despite being a fully-featured and extensible test tool, it boasts a simple
|
|||||||
syntax. Creating a test suite is as easy as writing a module with a couple of
|
syntax. Creating a test suite is as easy as writing a module with a couple of
|
||||||
functions
|
functions
|
||||||
|
|
||||||
::
|
.. code-block:: console
|
||||||
|
|
||||||
# content of test_sample.py
|
# content of test_sample.py
|
||||||
def func(x):
|
def func(x):
|
||||||
@@ -161,7 +161,7 @@ functions
|
|||||||
|
|
||||||
and then running the `py.test` command
|
and then running the `py.test` command
|
||||||
|
|
||||||
::
|
.. code-block:: console
|
||||||
|
|
||||||
$ py.test
|
$ py.test
|
||||||
=========================== test session starts ============================
|
=========================== test session starts ============================
|
||||||
@@ -193,7 +193,7 @@ Nose
|
|||||||
nose extends unittest to make testing easier.
|
nose extends unittest to make testing easier.
|
||||||
|
|
||||||
|
|
||||||
::
|
.. code-block:: console
|
||||||
|
|
||||||
$ pip install nose
|
$ pip install nose
|
||||||
|
|
||||||
@@ -210,7 +210,7 @@ tox
|
|||||||
tox is a tool for automating test environment management and testing against
|
tox is a tool for automating test environment management and testing against
|
||||||
multiple interpreter configurations
|
multiple interpreter configurations
|
||||||
|
|
||||||
::
|
.. code-block:: console
|
||||||
|
|
||||||
$ pip install tox
|
$ pip install tox
|
||||||
|
|
||||||
@@ -227,14 +227,14 @@ API and better assertions over the one available in previous versions of Python.
|
|||||||
|
|
||||||
If you're using Python 2.6 or below, you can install it with pip
|
If you're using Python 2.6 or below, you can install it with pip
|
||||||
|
|
||||||
::
|
.. code-block:: console
|
||||||
|
|
||||||
$ pip install unittest2
|
$ pip install unittest2
|
||||||
|
|
||||||
You may want to import the module under the name unittest to make porting code
|
You may want to import the module under the name unittest to make porting code
|
||||||
to newer versions of the module easier in the future
|
to newer versions of the module easier in the future
|
||||||
|
|
||||||
::
|
.. code-block:: python
|
||||||
|
|
||||||
import unittest2 as unittest
|
import unittest2 as unittest
|
||||||
|
|
||||||
@@ -253,7 +253,7 @@ mock
|
|||||||
|
|
||||||
mock is a library for testing in Python.
|
mock is a library for testing in Python.
|
||||||
|
|
||||||
::
|
.. code-block:: console
|
||||||
|
|
||||||
$ pip install mock
|
$ pip install mock
|
||||||
|
|
||||||
@@ -262,7 +262,7 @@ make assertions about how they have been used.
|
|||||||
|
|
||||||
For example, you can monkey patch a method
|
For example, you can monkey patch a method
|
||||||
|
|
||||||
::
|
.. code-block:: console
|
||||||
|
|
||||||
from mock import MagicMock
|
from mock import MagicMock
|
||||||
thing = ProductionClass()
|
thing = ProductionClass()
|
||||||
@@ -275,7 +275,7 @@ To mock classes or objects in a module under test, use the ``patch`` decorator.
|
|||||||
In the example below, an external search system is replaced with a mock that
|
In the example below, an external search system is replaced with a mock that
|
||||||
always returns the same result (but only for the duration of the test).
|
always returns the same result (but only for the duration of the test).
|
||||||
|
|
||||||
::
|
.. code-block:: console
|
||||||
|
|
||||||
def mock_search(self):
|
def mock_search(self):
|
||||||
class MockSearchQuerySet(SearchQuerySet):
|
class MockSearchQuerySet(SearchQuerySet):
|
||||||
@@ -287,7 +287,7 @@ always returns the same result (but only for the duration of the test).
|
|||||||
# not where the SearchForm class itself is imported from
|
# not where the SearchForm class itself is imported from
|
||||||
@mock.patch('myapp.SearchForm.search', mock_search)
|
@mock.patch('myapp.SearchForm.search', mock_search)
|
||||||
def test_new_watchlist_activities(self):
|
def test_new_watchlist_activities(self):
|
||||||
# get_search_results runs a search and iterates over the result
|
# get_search_results runs a search and iterates over the result
|
||||||
self.assertEqual(len(myapp.get_search_results(q="fish")), 3)
|
self.assertEqual(len(myapp.get_search_results(q="fish")), 3)
|
||||||
|
|
||||||
Mock has many other ways you can configure it and control its behavior.
|
Mock has many other ways you can configure it and control its behavior.
|
||||||
|
|||||||
Reference in New Issue
Block a user