From 4f4825a5b79092b7d07018f1c99f01bce14730cf Mon Sep 17 00:00:00 2001
From: David Winterbottom
Date: Fri, 8 Jun 2012 17:24:13 +0200
Subject: [PATCH 0001/1232] Fixed a few grammatical errors. Removed some
needless words.
---
docs/writing/style.rst | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index 91f1a1dfc..bbc57d340 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -1,15 +1,15 @@
Code Style
==========
-If you ask to Python programmers what they like the most in Python, they will
-often say it is its high readability. Indeed, a high level of readability of
-the code is at the heart of the design of the Python language, following the
+If you ask Python programmers what they like most in Python, they will
+often say its high readability. Indeed, a high level of readability
+is at the heart of the design of the Python language, following the
recognised fact that code is read much more often than it is written.
One reason for Python code to be easily read and understood is its relatively
complete set of Code Style guidelines and "Pythonic" idioms.
-On the opposite, when a veteran Python developper (a Pythonistas) point to some
+Moreover, when a veteran Python developer (a Pythonistas) point to some
parts of a code and say it is not "Pythonic", it usually means that these lines
of code do not follow the common guidelines and fail to express the intent in
what is considered the best (hear: most readable) way.
From 1d1727e65830f6b1b578d0020e6f2d867add2ef8 Mon Sep 17 00:00:00 2001
From: Philip Deuchler
Date: Fri, 8 Jun 2012 11:29:57 -0400
Subject: [PATCH 0002/1232] Removed 'more likely to be' when describing a pure
function's deterministic attributes, as pure functions by definition are
deterministic
---
docs/writing/structure.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index 60c11ca13..0fd4ca5b7 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -230,7 +230,7 @@ in the persistence layer, it is said to have a side-effect.
Carefully isolating functions with context and side-effects from functions with
logic (called pure functions) allow the following benefits:
-- Pure functions are more likely to be deterministic: given a fixed input,
+- Pure functions are deterministic: given a fixed input,
the output will always be the same.
- Pure functions are much easier to change or replace if they need to
From e54f0c3376c8917b876cfe2622c3f4c98af99188 Mon Sep 17 00:00:00 2001
From: lepture
Date: Sat, 9 Jun 2012 12:53:29 +0800
Subject: [PATCH 0003/1232] fix writing style line continuations to fit pep8
---
docs/writing/style.rst | 13 ++++++++-----
1 file changed, 8 insertions(+), 5 deletions(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index bbc57d340..d2262a483 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -581,11 +581,14 @@ and square braces.
.. code-block:: python
- my_very_big_string = ("For a long time I used to go to bed early. Sometimes, "
- "when I had put out my candle, my eyes would close so quickly that I had not even "
- "time to say “I’m going to sleep.”")
-
- from some.deep.module.inside.a.module import (a_nice_function, another_nice_function,
+ my_very_big_string = (
+ "For a long time I used to go to bed early. Sometimes, "
+ "when I had put out my candle, my eyes would close so quickly "
+ "that I had not even time to say “I’m going to sleep.”"
+ )
+
+ from some.deep.module.inside.a.module import (a_nice_function,
+ another_nice_function,
yet_another_nice_functio)
However, more often than not having to split long logical line is a sign that
From 911865980b03d2f08c687549e24557e612a0f545 Mon Sep 17 00:00:00 2001
From: Kenneth Reitz
Date: Sat, 9 Jun 2012 01:08:55 -0400
Subject: [PATCH 0004/1232] #168
---
docs/writing/style.rst | 13 ++++++-------
1 file changed, 6 insertions(+), 7 deletions(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index d2262a483..0be34fcd3 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -2,7 +2,7 @@ Code Style
==========
If you ask Python programmers what they like most in Python, they will
-often say its high readability. Indeed, a high level of readability
+often say its high readability. Indeed, a high level of readability
is at the heart of the design of the Python language, following the
recognised fact that code is read much more often than it is written.
@@ -253,7 +253,7 @@ will not need that variable, use ``__``:
double underscore instead is just as clear and almost as convenient,
and eliminates the risk of accidentally interfering with either of
these other use cases.
-
+
Create a length-N list of the same thing
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -285,10 +285,10 @@ This will set the value of the variable *word* to 'spam'. This idiom can be appl
Sometimes we need to search through a collection of things. Let's look at two options: lists and dictionaries.
Take the following code for example::
-
+
d = {'s': [], 'p': [], 'a': [], 'm': []}
l = ['s', 'p', 'a', 'm']
-
+
def lookup_dict(d):
return 's' in d
@@ -587,9 +587,8 @@ and square braces.
"that I had not even time to say “I’m going to sleep.”"
)
- from some.deep.module.inside.a.module import (a_nice_function,
- another_nice_function,
- yet_another_nice_functio)
+ from some.deep.module.inside.a.module import (
+ a_nice_function, another_nice_function, yet_another_nice_function)
However, more often than not having to split long logical line is a sign that
you are trying to do too many things at the same time, which may hinder
From bdcfd1e221f996699522295207a0138522f3ada6 Mon Sep 17 00:00:00 2001
From: Jens Rantil
Date: Sun, 10 Jun 2012 18:53:37 +0200
Subject: [PATCH 0005/1232] Minor spelling fix
---
docs/writing/tests.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/tests.rst b/docs/writing/tests.rst
index 717d26e89..0a8479dc1 100644
--- a/docs/writing/tests.rst
+++ b/docs/writing/tests.rst
@@ -47,7 +47,7 @@ Some general rules of testing:
catching test are among the most valuable piece of code in your project.
- Use long and descriptive names for testing functions. The style guide here is
- slighlty different than that of running code, where short names are often
+ slightly different than that of running code, where short names are often
preferred. The reason is testing functions are never called explicitely.
``square()`` or even ``sqr()`` is ok in running code, but in testing code you
would has names such as ``test_square_of_number_2()``,
From be8a466bd0c278c5a992e4ede5effec4f7e39531 Mon Sep 17 00:00:00 2001
From: Jens Rantil
Date: Sun, 10 Jun 2012 19:53:34 +0200
Subject: [PATCH 0006/1232] Fixing a broken bullet list
---
docs/dev/env.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/dev/env.rst b/docs/dev/env.rst
index 65225a5e1..2c4ba0356 100644
--- a/docs/dev/env.rst
+++ b/docs/dev/env.rst
@@ -252,7 +252,7 @@ most out of using Python interactively. Its main components are:
* Powerful Python shells (terminal- and Qt-based).
* A web-based notebook with the same core features but support for rich media,
-text, code, mathematical expressions and inline plots.
+ text, code, mathematical expressions and inline plots.
* Support for interactive data visualization and use of GUI toolkits.
* Flexible, embeddable interpreters to load into your own projects.
* Tools for high level and interactive parallel computing.
From 56c0ae7992e25b2a029a1416fec220abbb1ff935 Mon Sep 17 00:00:00 2001
From: Jens Rantil
Date: Sun, 10 Jun 2012 19:59:12 +0200
Subject: [PATCH 0007/1232] Correct capitalization of "NumPy"
---
docs/scenarios/scientific.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/scenarios/scientific.rst b/docs/scenarios/scientific.rst
index 37e60bd3a..9c8d70890 100644
--- a/docs/scenarios/scientific.rst
+++ b/docs/scenarios/scientific.rst
@@ -16,7 +16,7 @@ for matrix operations). The main libraries used are NumPy and SciPy
Libraries
:::::::::
-Numpy
+NumPy
-----
`NumPy `_ is a low level library written in C (and
FORTRAN) for high level mathematical functions. NumPy cleverly overcomes the
From d0774acdf300e7c72aade60864c36f9e2abd16c9 Mon Sep 17 00:00:00 2001
From: Jens Rantil
Date: Sun, 10 Jun 2012 20:00:32 +0200
Subject: [PATCH 0008/1232] Add cross references to `NumPy`and `SciPy`
---
docs/scenarios/scientific.rst | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/docs/scenarios/scientific.rst b/docs/scenarios/scientific.rst
index 9c8d70890..0b2c16510 100644
--- a/docs/scenarios/scientific.rst
+++ b/docs/scenarios/scientific.rst
@@ -11,7 +11,8 @@ and it performs really well.
Due to its high performance nature, scientific computing in python often refers
to external libraries, typically written in faster languages (like C, or FORTRAN
-for matrix operations). The main libraries used are NumPy and SciPy
+for matrix operations). The main libraries used are `NumPy`_ and
+`SciPy`_.
Libraries
:::::::::
From a7d4459c956446ca588af4cd51d55e1af13acf02 Mon Sep 17 00:00:00 2001
From: Jens Rantil
Date: Sun, 10 Jun 2012 22:17:48 +0200
Subject: [PATCH 0009/1232] Another minor spelling fix
---
docs/intro/duction.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/intro/duction.rst b/docs/intro/duction.rst
index 83b3aa713..e0d4180bc 100644
--- a/docs/intro/duction.rst
+++ b/docs/intro/duction.rst
@@ -18,7 +18,7 @@ include:
Python is sometimes described with the words "batteries included"
for its extensive
- `stanadard library `_, which can
+ `standard library `_, which can
includes modules for regular expressions, file IO, fraction handling,
object serialization, and much more.
From 62e59a57e48ca6a52c6ad649731a0cf324551e5b Mon Sep 17 00:00:00 2001
From: Kyle Roberts
Date: Wed, 13 Jun 2012 21:34:08 -0400
Subject: [PATCH 0010/1232] Add code example to demonstrate proper string
concatenation.
The text does a good job of explaining which route to take when
concatenating strings, but the mention of "join" might mean nothing to
beginners without a concrete example.
---
docs/writing/structure.rst | 20 ++++++++++++++++++++
1 file changed, 20 insertions(+)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index 0fd4ca5b7..eecf700c2 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -391,6 +391,26 @@ 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
full string is needed.
+**Bad**
+
+.. code-block:: python
+
+ # create a concatenated string from 0 to 19 (e.g. "012..1819")
+ nums = ""
+ for n in range(20):
+ nums += str(n) # slow and inefficient
+ print nums
+
+**Good**
+
+.. code-block:: python
+
+ # create a concatenated string from 0 to 19 (e.g. "012..1819")
+ nums = []
+ for n in range(20):
+ nums.append(str(n))
+ print "".join(nums) # much more efficient
+
Vendorizing Dependencies
------------------------
From 226ad55c515ecaeff3e20614d89f69a2a20e4b30 Mon Sep 17 00:00:00 2001
From: Ian Cordasco
Date: Fri, 15 Jun 2012 14:08:38 -0400
Subject: [PATCH 0011/1232] Improve upon string concatenation section.
---
docs/writing/structure.rst | 26 +++++++++++++++++++++++++-
1 file changed, 25 insertions(+), 1 deletion(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index eecf700c2..6765f1848 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -389,7 +389,9 @@ One peculiarity of Python that can surprise beginners is that
strings are immutable. This means that when constructing a string from
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
-full string is needed.
+full string is needed. One thing to notice, however, is that list
+comprehensions are better and faster than constructing a list in a loop
+with calls to append().
**Bad**
@@ -411,6 +413,28 @@ full string is needed.
nums.append(str(n))
print "".join(nums) # much more efficient
+**Best**
+
+.. code-block:: python
+
+ # create a concatenated string from 0 to 19 (e.g. "012..1819")
+ print "".join([str(n) for n in range(20)])
+
+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
+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()
+should be your preferred method.
+
+.. code-block:: python
+
+ foo = 'foo'
+ bar = 'bar'
+
+ foobar = foo + bar # This is good
+ foo += 'ooo' # This is bad, instead you should do:
+ foo = ''.join([foo, 'ooo'])
+
Vendorizing Dependencies
------------------------
From 513bb5fe5146cbc9d5454e93abb7c7a61c050e22 Mon Sep 17 00:00:00 2001
From: guibog
Date: Sun, 24 Jun 2012 21:47:24 +0800
Subject: [PATCH 0012/1232] Adding nested unpacking
---
docs/writing/style.rst | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index 0be34fcd3..4198c276b 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -232,6 +232,12 @@ You can use this to swap variables, as well:
a, b = b, a
+Nested unpacking works too:
+
+.. code-block:: python
+
+ a, (b, c) = 1, (2, 3)
+
Create an ignored variable
~~~~~~~~~~~~~~~~~~~~~~~~~~
From 810c637f6cb49e7f1755d84a2abfc0578fbf6477 Mon Sep 17 00:00:00 2001
From: guibog
Date: Sun, 24 Jun 2012 22:31:09 +0800
Subject: [PATCH 0013/1232] Adding a bit about returning values
---
docs/writing/style.rst | 43 ++++++++++++++++++++++++++++++++++++++++++
1 file changed, 43 insertions(+)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index 4198c276b..b0279b9d6 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -208,6 +208,49 @@ This will guarantee a better separation of duties and easier modifications of
existing code, and it will always be possible to publicize a private property,
while privatising a public property might be a much harder operation.
+Returning values
+~~~~~~~~~~~~~~~~
+
+Python functions return a value, and you can control this return value with the
+return statement for all of them but the object constructor `__init__()` and the
+special case of generators.
+
+When a function grows in complexity is not uncommon to use multiple return statements
+inside the function's body. However, in order to keep a clear intent and a sustainable
+readability level, it is preferable to avoid returning meaningful values from many
+output point in the body.
+
+There are two main cases for returning values in a function: The result of the function
+return when it has been processed normally, and the error cases that indicate a wrong
+input paramter or any other reason for the function to not be able to complete its
+computation or task.
+
+If you do not wish to raise exceptions for the second case, then returning a value, such
+as None or False, indicating that the function could not perform correctly might be needed. In this
+case, it is better to return as early as the incorrect context has been detected. It will
+help to flatten the structure of the function: all the code after the return-because-of-error
+statement can assume the condition is met to further compute the function's main result.
+Having multiple such return statement is often necessary.
+
+However, when a function has multiple main exit points for its normal course, it becomes
+difficult to debug the returned result, and it may be preferable to keep a single exit
+point. This will also help factoring out some code paths, and the multiple exit point
+is a probable indication that such a refactoring is needed.
+
+.. code-block:: python
+
+ def complex_function(a, b, c):
+ if not a:
+ return None # Raising an exception might be better
+ if not b:
+ return None # Raising an exception might be better
+ # Some complex code trying to compute x from a, b and c
+ # Resist temptation to return x if succeeded
+ if not x:
+ # Some Plan-B computation of x
+ return x # One single exit point for the returned value x will help
+ # when maintaining the code.
+
Idioms
------
From d262c89293cdcc272b817f886c437d5a2e6deb50 Mon Sep 17 00:00:00 2001
From: Estevan Pequeno
Date: Tue, 3 Jul 2012 20:10:06 -0500
Subject: [PATCH 0014/1232] remove deprecated flag
---
docs/starting/install/linux.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/starting/install/linux.rst b/docs/starting/install/linux.rst
index 06aeb9ee8..5032ed216 100644
--- a/docs/starting/install/linux.rst
+++ b/docs/starting/install/linux.rst
@@ -58,7 +58,7 @@ project's directory
.. code-block:: console
- $ virtualenv --distribute venv
+ $ virtualenv venv
To use an environment, run ``source venv/bin/activate``. Your command prompt
will change to show the active environment. Once you have finished working in
From f05bad383937c5601823439b50851d94d1526739 Mon Sep 17 00:00:00 2001
From: Estevan Pequeno
Date: Tue, 3 Jul 2012 21:08:42 -0500
Subject: [PATCH 0015/1232] module naming
---
docs/writing/structure.rst | 19 ++++++++++++++++---
1 file changed, 16 insertions(+), 3 deletions(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index 6765f1848..61d83ab14 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -75,9 +75,22 @@ As soon as you use `import` statements you use modules. These can be either buil
modules such as `os` and `sys`, third-party modules you have installed in your
environment, or your project's internal modules.
-Nothing special is required for a Python file to be a module, but the import
-mechanism needs to be understood in order to use this concept properly and avoid
-some issues.
+To keep in line with the style guide, keep module names short, lowercase, and
+be sure to avoid using special symbols like the dot (.) or question mark (?).
+So a file name like `my.spam.py` is one you should try to avoid! Naming this way
+will interfere with the way python looks for modules.
+
+In this example python expects to find a "spam.py" file in a folder named "my"
+which is not the case. There is an
+`example `_
+ of how the dot should be used available in the python docs.
+
+If you'd like you could name it as `my_spam.py` but even our friend the
+underscore should not be seen often in module names.
+
+Aside for some naming restrictions, nothing special is required for a Python file
+to be a module, but the import mechanism needs to be understood in order to use
+this concept properly and avoid some issues.
Concretely, the `import modu` statement will look for the proper file, which is
`modu.py` in the same directory as the caller if it exists. If it is not
From fcefab992cdf699a9c84e9aa56c0c1ed609f01e6 Mon Sep 17 00:00:00 2001
From: Estevan Pequeno
Date: Tue, 3 Jul 2012 21:24:08 -0500
Subject: [PATCH 0016/1232] minor editing
---
docs/writing/structure.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index 61d83ab14..0d2989b3e 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -289,7 +289,7 @@ clearer and thus preferred.
# Do something
# bar() is decorated
-Using this mechanism is useful for separating concerns and avoiding
+This mechanism is useful for separating concerns and avoiding
external un-related logic 'polluting' the core logic of the function
or method. A good example of a piece of functionality that is better handled
with decoration is memoization or caching: you want to store the results of an
From 167d566650bcb2ca5156d7af2b69f7858bda3c80 Mon Sep 17 00:00:00 2001
From: Estevan Pequeno
Date: Tue, 3 Jul 2012 22:19:31 -0500
Subject: [PATCH 0017/1232] add stub
---
docs/writing/structure.rst | 17 +++++++++++++++--
1 file changed, 15 insertions(+), 2 deletions(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index 0d2989b3e..b1cc5de23 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -1,9 +1,22 @@
Structuring Your Project
========================
-Structuring your project properly is extremely important.
+When we say structure we mean the decisions you make concerning
+how your project best meets its objective. We need to consider how to
+best leverage Python's features to create clean, effective code.
+In practical terms structure means the actual files and folders that
+comprise your project as well as the way dependencies are handled within
+the code itself.
+
+How does data flow through the project? What features and functions
+can be grouped together and isolated? By answering questions like these
+you can begin to plan, in a broad sense, what your finished product will
+look like.
+
+In this section we take a closer look at Python's module and import
+systems as they are the central element to enforcing structure in your
+project.
-.. todo:: Fill in "Structuring Your Project" stub
Structure is Key
----------------
From 63a2bfc514e0e4982fdaa64cd1cf63e37cfeaba8 Mon Sep 17 00:00:00 2001
From: Ryan Campbell
Date: Tue, 3 Jul 2012 21:31:10 -0600
Subject: [PATCH 0018/1232] Fix awkward wording in "Comments" section
---
docs/writing/documentation.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/documentation.rst b/docs/writing/documentation.rst
index 62a81658a..8d3a8f1a3 100644
--- a/docs/writing/documentation.rst
+++ b/docs/writing/documentation.rst
@@ -70,7 +70,7 @@ misleading for the maintainers, slow down considerably bug hunting or
refactoring, and then, when discovered wrong, they will throw suspicion on all
other comments in the code, regardless of their individual correctness.
-**No need comments for perfect code...** An hypothetical perfectly readable
+**There's no need to comment perfect code...** An hypothetical perfectly readable
code, with a crystal clear logic stream, expressive variable and function
names, orthogonal segmentation passing exactly between the flesh and the bones,
and no implicit assumptions of any kind, would not require any comment at all.
From 7d66ac6d2059a31732c38169147e7bac8e983acd Mon Sep 17 00:00:00 2001
From: Ryan Campbell
Date: Tue, 3 Jul 2012 21:32:00 -0600
Subject: [PATCH 0019/1232] Fix spelling in documentation article
---
docs/writing/documentation.rst | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/docs/writing/documentation.rst b/docs/writing/documentation.rst
index 8d3a8f1a3..a598d4306 100644
--- a/docs/writing/documentation.rst
+++ b/docs/writing/documentation.rst
@@ -78,7 +78,7 @@ When striving for coding excellence, it is useful to see any existing comment,
or any feeling of a need for a comment, as the sign that the code do not
express clearly enough its intent and can be improved.
-**.. but no code is perfect.** Perfect code is a chimere, it exists only in
+**.. but no code is perfect.** Perfect code is a chimera, it exists only in
our dreams. In real life, a code base is full of trade offs, and comments are
often needed in the most difficult parts. Moreover, any special case, any
obscure hack, any monkey patch and any ugly workaround MUST be signaled and
@@ -87,15 +87,15 @@ explained by a proper comment. This should be enforced by the law!
**TODOs** are special comments that a developer write as a reminder for later
use. It is said that its original intent was that someone might, one day,
search for the string "TODO" in the code base and actually roll their sleeves
-and start *to do the TODOs*. There is no avalaible record that it ever
+and start *to do the TODOs*. There is no available record that it ever
happened. However, TODOs comment are still very useful, because they mark the
current limits of the code, and it is not unlikely that, when required to add a
new behavior to the actual code, looking at the TODOs will show where to start.
**Do not use triple-quote strings to comment code.** A common operation when
-modifiying code is to comment out some lines or even a full function or class
+modifying code is to comment out some lines or even a full function or class
definition. This can be done by adding triple-quotes around the code block to
-be skipped, but this is not a good pratice, because line-oriented command-line
+be skipped, but this is not a good practice, because line-oriented command-line
tools such as ``grep`` will not be aware that the commented code is inactive.
It is better to add hashes at the proper indentation level for every commented
line. Good editors allow to do this with few keystrokes (ctrl-v on Vim).
@@ -156,7 +156,7 @@ Block comment styling should be used when commenting out multiple lines of code.
Paragraphs inside a block comment are separated by a line containing a
single #.
-Inline comments are used for individual lines and should be used sparingly.: ::
+In-line comments are used for individual lines and should be used sparingly.: ::
An inline comment is a comment on the same line as a statement. Inline
comments should be separated by at least two spaces from the statement.
From 28d211f6f52fe26332536761d669dae4eb704fdc Mon Sep 17 00:00:00 2001
From: Estevan Pequeno
Date: Tue, 3 Jul 2012 22:36:07 -0500
Subject: [PATCH 0020/1232] edit stub
---
docs/writing/structure.rst | 19 ++++++++++---------
1 file changed, 10 insertions(+), 9 deletions(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index b1cc5de23..ee328ee92 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -1,21 +1,22 @@
Structuring Your Project
========================
-When we say structure we mean the decisions you make concerning
+By "structure" we mean the decisions you make concerning
how your project best meets its objective. We need to consider how to
best leverage Python's features to create clean, effective code.
-In practical terms structure means the actual files and folders that
-comprise your project as well as the way dependencies are handled within
-the code itself.
+In practical terms, "structure" means making clean code whose logic and
+dependencies are clear as well as how the files and folders are organized
+in the filesystem.
-How does data flow through the project? What features and functions
-can be grouped together and isolated? By answering questions like these
-you can begin to plan, in a broad sense, what your finished product will
-look like.
+Which functions should go into which modules? How does data flow through
+the project? What features and functions can be grouped together and
+isolated? By answering questions like these you can begin to plan, in
+a broad sense, what your finished product will look like.
In this section we take a closer look at Python's module and import
systems as they are the central element to enforcing structure in your
-project.
+project. We then discuss various perspectives on how to build code which
+can be extended and tested reliably.
Structure is Key
From e6cef5d19e543d61acfe146332fce349cf9e4dc5 Mon Sep 17 00:00:00 2001
From: Ryan Campbell
Date: Tue, 3 Jul 2012 21:38:06 -0600
Subject: [PATCH 0021/1232] Fix spelling in learning.rst
---
docs/intro/learning.rst | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/docs/intro/learning.rst b/docs/intro/learning.rst
index 22bb10b95..0f38d6eeb 100644
--- a/docs/intro/learning.rst
+++ b/docs/intro/learning.rst
@@ -136,7 +136,7 @@ as writing C extensions.
The Python Language Reference
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-This is Python's reference manual, it covers the syntax and the core symantics of the
+This is Python's reference manual, it covers the syntax and the core semantics of the
language.
- `The Python Language Reference `_
\ No newline at end of file
+ `The Python Language Reference `_
From bd770496a29db57659c84aa88ef5a3860646d4b1 Mon Sep 17 00:00:00 2001
From: Ryan Campbell
Date: Tue, 3 Jul 2012 21:40:36 -0600
Subject: [PATCH 0022/1232] fix spelling in env.rst
---
docs/dev/env.rst | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/docs/dev/env.rst b/docs/dev/env.rst
index 2c4ba0356..b1678e500 100644
--- a/docs/dev/env.rst
+++ b/docs/dev/env.rst
@@ -15,7 +15,7 @@ VIM
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
aid python development. If you only develop in Python, a good start is to set
-the default settings for indentation and linewrapping to values compliant with
+the default settings for indentation and line-wrapping to values compliant with
`PEP 8 `_. In your home directory,
open a file called `.vimrc` and add the following lines: ::
@@ -151,7 +151,7 @@ Create a virtual environment for a project::
$ cd my_project
$ virtualenv venv
-``virtualenv venv`` will create a folder in the currect directory
+``virtualenv venv`` will create a folder in the current directory
which will contain the Python executable files, and a copy of the ``pip``
library which you can use to install other packages. The name of the
virtual environment (in this case, it was ``venv``) can be anything;
From d6f0ec1680570ade2d6e5edba2442525e49e516d Mon Sep 17 00:00:00 2001
From: Ryan Campbell
Date: Tue, 3 Jul 2012 21:43:08 -0600
Subject: [PATCH 0023/1232] Fix spelling in styleguide.rst
---
docs/notes/styleguide.rst | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/docs/notes/styleguide.rst b/docs/notes/styleguide.rst
index a96c7b6c2..edaecc1fb 100644
--- a/docs/notes/styleguide.rst
+++ b/docs/notes/styleguide.rst
@@ -7,7 +7,7 @@ The Guide Style Guide
As with all documentation, having a consistent formating helps make the
document more understandable. In order to make The Guide easier to digest,
all contributions should fit within the rules of this style guide where
-approriate.
+appropriate.
The Guide is written as :ref:`restructuredtext-ref`.
@@ -29,9 +29,9 @@ Strive to keep any contributions relevant to the :ref:`purpose of The Guide
Be sure to describe what and why you are linking.
* `Cite `_
references where needed.
-* If a subject isn't directly relevant to Python, but useful in conjuction
+* If a subject isn't directly relevant to Python, but useful in conjunction
with Python (ex: Git, Github, Databases), reference by linking to useful
- resouces and describe why it's useful to Python.
+ resources and describe why it's useful to Python.
* When in doubt, ask.
Headings
@@ -115,7 +115,7 @@ Externally Linking
Read the `Sphinx Tutorial `_
* Avoid using labels such as "click here", "this", etc. preferring
- decriptive labels (SEO worthy) instead.
+ descriptive labels (SEO worthy) instead.
Linking to Sections in The Guide
--------------------------------
From 1cfed040f7595ba58b10539992f942fe7306fd5a Mon Sep 17 00:00:00 2001
From: Ryan Campbell
Date: Tue, 3 Jul 2012 21:46:52 -0600
Subject: [PATCH 0024/1232] Fix spelling in install/osx.rst
---
docs/starting/install/osx.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/starting/install/osx.rst b/docs/starting/install/osx.rst
index 7b8603cf8..3da84a76b 100644
--- a/docs/starting/install/osx.rst
+++ b/docs/starting/install/osx.rst
@@ -35,7 +35,7 @@ simply run
$ /usr/bin/ruby -e "$(/usr/bin/curl -fsSL https://raw.github.com/mxcl/homebrew/master/Library/Contributions/install_homebrew.rb)"
-Then, insert the Homebrew directory at the top of your ``PATH`` enviornment
+Then, insert the Homebrew directory at the top of your ``PATH`` environment
variable. You can do this by adding the following line at the bottom of your
``~/.bashrc`` file
From 0ff26166c62f78d3b911e90e17173d3b04d6b5d0 Mon Sep 17 00:00:00 2001
From: Ryan Campbell
Date: Tue, 3 Jul 2012 21:48:42 -0600
Subject: [PATCH 0025/1232] Fix spelling in structure.rst
---
docs/writing/structure.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index 6765f1848..3adf2dcdf 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -279,7 +279,7 @@ clearer and thus preferred.
Using this mechanism is useful for separating concerns and avoiding
external un-related logic 'polluting' the core logic of the function
or method. A good example of a piece of functionality that is better handled
-with decoration is memoization or caching: you want to store the results of an
+with decoration is memorization or caching: you want to store the results of an
expensive function in a table and use them directly instead of recomputing
them when they have already been computed. This is clearly not part
of the function logic.
From e3eac0c78cdffcd3d539f6167718a8c2016ec305 Mon Sep 17 00:00:00 2001
From: Ryan Campbell
Date: Tue, 3 Jul 2012 21:55:49 -0600
Subject: [PATCH 0026/1232] Fix spelling in style.rst
---
docs/writing/style.rst | 28 ++++++++++++++--------------
1 file changed, 14 insertions(+), 14 deletions(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index b0279b9d6..462ffba0d 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -41,7 +41,7 @@ most explicit and straightforward manner is preferred.
def make_complex(x, y):
return {'x': x, 'y': y}
-In the good code above, x and y are explicitely received from
+In the good code above, x and y are explicitly received from
the caller, and an explicit dictionary is returned. The developer
using this function knows exactly what to do by reading the
first and last lines, which is not the case with the bad example.
@@ -50,7 +50,7 @@ One statement per line
~~~~~~~~~~~~~~~~~~~~~~
While some compound statements such as list comprehensions are
-allowed and appreciated for their brevity and their expressivity,
+allowed and appreciated for their brevity and their expressiveness,
it is bad practice to have two disjoint statements on the same line.
**Bad**
@@ -107,10 +107,10 @@ passed another value.
Calling a function with keyword arguments can be done in multiple ways in Python,
for example it is possible to follow the order of arguments in the definition without
-explicitely naming the arguments, like in ``send('Hello', 'World', 'Cthulhu`, 'God')``,
+explicitly naming the arguments, like in ``send('Hello', 'World', 'Cthulhu`, 'God')``,
sending a blank carbon copy to God. It would also be possible to name arguments in
another order, like in ``send('Hello again', 'World', bcc='God', cc='Cthulhu')``.
-Those two possibilities are better avoided whitout any strong reason to not
+Those two possibilities are better avoided without any strong reason to not
follow the syntax that is the closest to the function definition: ``send('Hello',
'World', cc='Cthulhu', bcc='God')``.
@@ -132,13 +132,13 @@ However, this construct has some drawback and should be used with caution. If a
function receives a list of arguments of the same nature, it is often more
clear to define it as a function of one argument, that argument being a list or
any sequence. Here, if ``send`` has multiple recipients, it is better to define
-it explicitely: ``send(message, recipients)`` and call it with ``send('Hello',
+it explicitly: ``send(message, recipients)`` and call it with ``send('Hello',
['God', 'Mom', 'Cthulhu'])``. This way, the user of the function can manipulate
-the recipient list as a list beforhand, and it opens the possibility to pass
-any sequence, inculding iterators, that cannot be unpacked as other sequences.
+the recipient list as a list beforehand, and it opens the possibility to pass
+any sequence, including iterators, that cannot be unpacked as other sequences.
The **arbitrary keyword argument dictionary** is the last way to pass arguments
-to functions. If the function requires an undetermined serie of named
+to functions. If the function requires an undetermined series of named
arguments, it is possible to used the ``**kwargs`` construct. In the function
body, ``kwargs`` will be a dictionary of all the passed named arguments that
have not been caught be other keyword argument in the function signature.
@@ -149,8 +149,8 @@ proven necessity to use them, and they should not be used if the simpler and
clearer construct is sufficient to express the function's intention.
It is up to the programmer writing the function to determine which arguments
-are positional argmuents and which are optional keyword arguments, and to
-decide wheter to use the advanced techniques of arbitrary argument passing. If
+are positional arguments and which are optional keyword arguments, and to
+decide whether to use the advanced techniques of arbitrary argument passing. If
the advices above are followed wisely, it is possible and enjoyable to write
Python functions that are:
@@ -164,7 +164,7 @@ Avoid the magical wand
A powerful tool for hackers, Python comes with a very rich set of hooks and
tools allowing to do almost any kind of tricky tricks. For instance, it is
-possible to change how objects are created and instanciated, it is possible to
+possible to change how objects are created and instantiated, it is possible to
change how the Python interpreter imports modules, it is even possible (and
recommended if needed) to embed C routines in Python.
@@ -222,7 +222,7 @@ output point in the body.
There are two main cases for returning values in a function: The result of the function
return when it has been processed normally, and the error cases that indicate a wrong
-input paramter or any other reason for the function to not be able to complete its
+input parameter or any other reason for the function to not be able to complete its
computation or task.
If you do not wish to raise exceptions for the second case, then returning a value, such
@@ -610,7 +610,7 @@ sometime but is preferably avoided, because of its fragility: a white space
added to the end of the line, after the backslash, will break the code and may
have unexpected results.
-A prefered solution is to use parenthesis around your elements. Left with an
+A preferred solution is to use parenthesis around your elements. Left with an
unclosed parenthesis on an end-of-line the Python interpreter will join the
next line until the parenthesis is closed. The same behavior holds for curly
and square braces.
@@ -624,7 +624,7 @@ and square braces.
time to say “I’m going to sleep.”"""
from some.deep.module.inside.a.module import a_nice_function, another_nice_function, \
- yet_another_nice_functio
+ yet_another_nice_function
**Good**:
From 1d63c913bf524dbbed03726373ace42e99123231 Mon Sep 17 00:00:00 2001
From: Ryan Campbell
Date: Tue, 3 Jul 2012 21:56:06 -0600
Subject: [PATCH 0027/1232] Fix spelling in writing/tests.rst
---
docs/writing/tests.rst | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/docs/writing/tests.rst b/docs/writing/tests.rst
index 0a8479dc1..12590b6f5 100644
--- a/docs/writing/tests.rst
+++ b/docs/writing/tests.rst
@@ -3,7 +3,7 @@ Testing Your Code
Testing your code is very important.
-Getting used to writting the testing code and the running code in parallel is
+Getting used to writing the testing code and the running code in parallel is
now considered a good habit. Used wisely, this method helps you define more
precisely your code's intent and have a more decoupled architecture.
@@ -39,7 +39,7 @@ Some general rules of testing:
- If you are in the middle of a development and have to interrupt your work, it
is a good idea to write a broken unit test about what you want to develop next.
- When comming back to work, you will have a pointer to where you were and get
+ When coming back to work, you will have a pointer to where you were and get
faster on tracks.
- The first step when you are debugging your code is to write a new test
@@ -48,7 +48,7 @@ Some general rules of testing:
- Use long and descriptive names for testing functions. The style guide here is
slightly different than that of running code, where short names are often
- preferred. The reason is testing functions are never called explicitely.
+ preferred. The reason is testing functions are never called explicitly.
``square()`` or even ``sqr()`` is ok in running code, but in testing code you
would has names such as ``test_square_of_number_2()``,
``test_square_negative_number()``. These function names are displayed when a
@@ -61,7 +61,7 @@ Some general rules of testing:
purpose is unclear is not very helpful is this case.
- Another use of the testing code is as an introduction to new developers. When
- someone will have to work on the code base, runnning and reading the related
+ someone will have to work on the code base, running and reading the related
testing code is often the best they can do. They will or should discover the
hot spots, where most difficulties arise, and the corner cases. If they have
to add some functionality, the first step should be to add a test and, by this
@@ -214,7 +214,7 @@ multiple interpreter configurations
$ pip install tox
-tox allows you to configure complicatated multi-parameter test matrices via a
+tox allows you to configure complicated multi-parameter test matrices via a
simple ini-style configuration file.
`tox `_
@@ -222,7 +222,7 @@ simple ini-style configuration file.
Unittest2
---------
-unittest2 is a a backport of Python 2.7's unittest module which has an improved
+unittest2 is a backport of Python 2.7's unittest module which has an improved
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
From e5caa56e887bec6578680b0bdc64179509ec5d8c Mon Sep 17 00:00:00 2001
From: Daniel Schauenberg
Date: Wed, 4 Jul 2012 02:09:35 -0300
Subject: [PATCH 0028/1232] add notes about vim usage with syntastic
---
docs/dev/env.rst | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/docs/dev/env.rst b/docs/dev/env.rst
index 2c4ba0356..d6776b3f1 100644
--- a/docs/dev/env.rst
+++ b/docs/dev/env.rst
@@ -50,6 +50,16 @@ order to do this, add the following lines to your `vimrc`::
autocmd BufWritePost *.py call Pyflakes()
autocmd BufWritePost *.py call Pep8()
+If you are already using syntastic_ you can enable it to run Pyflakes on write
+and show errors and warnings in the quickfix window. An example configuration
+to do that which also shows status and warning messages in the statusbar would be::
+
+ set statusline+=%#warningmsg#
+ set statusline+=%{SyntasticStatuslineFlag()}
+ set statusline+=%*
+ let g:syntastic_auto_loc_list=1
+ let g:syntastic_loc_list_height=5
+
.. _indent: http://www.vim.org/scripts/script.php?script_id=974
.. _syntax: http://www.vim.org/scripts/script.php?script_id=790
@@ -57,6 +67,7 @@ order to do this, add the following lines to your `vimrc`::
.. _vim-pyflakes: https://github.com/nvie/vim-pyflakes
.. _PEP8: http://pypi.python.org/pypi/pep8/
.. _vim-pep8: https://github.com/nvie/vim-pep8
+.. _syntastic: https://github.com/scrooloose/syntastic
.. todo:: add supertab notes
From d8c4d3612e9e0e671f1706fa164a6621aa4f5a46 Mon Sep 17 00:00:00 2001
From: Daniel Schauenberg
Date: Wed, 4 Jul 2012 02:27:18 -0300
Subject: [PATCH 0029/1232] add section about travis-ci
---
docs/scenarios/ci.rst | 35 +++++++++++++++++++++++++++++++++--
1 file changed, 33 insertions(+), 2 deletions(-)
diff --git a/docs/scenarios/ci.rst b/docs/scenarios/ci.rst
index 659f44060..3a80c70b3 100644
--- a/docs/scenarios/ci.rst
+++ b/docs/scenarios/ci.rst
@@ -53,5 +53,36 @@ which provides the following features:
Travis-CI
---------
-
-.. todo:: Write about travis-ci
+`Travis-CI `_ is a distributed CI server which builds tests
+for open source projects for free. It provides multiple workers to run Python tests
+on and seamlessly integrates with Github. You can even have it comment on your Pull
+Requests whether this particular changeset breaks the build or not. So if you are
+hosting your code on Github, travis-ci is a great and easy way to get started with
+Continuous Integration.
+
+In order to get started, add a ``.travis.yml`` file to your repository with this
+example content::
+
+ language: python
+ python:
+ - "2.5"
+ - "2.6"
+ - "2.7"
+ - "3.1"
+ - "3.2"
+ # command to install dependencies
+ script: python tests/test_all_of_the_units.py
+ branches:
+ only:
+ - master
+
+
+This will get your project tested on all the listed Python versions by running the given
+script and only build the master branch. There are a lot more options you can enable, like
+notifications, before and after steps and much more. The
+`travis-ci docs `_ explain all of those and are very
+thorough.
+
+In order to activate testing for your project, go to `the travis-ci site `_
+and login with your Github account. Then activate your project in your profile settings and that's
+it. From now on, your project's tests will be run on every push to Github.
From 1fdb37aad89febbdd8349bc2247a3c090acaabf2 Mon Sep 17 00:00:00 2001
From: Kenneth Reitz
Date: Wed, 4 Jul 2012 02:16:48 -0400
Subject: [PATCH 0030/1232] Revert "remove deprecated flag"
This reverts commit d262c89293cdcc272b817f886c437d5a2e6deb50.
---
docs/starting/install/linux.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/starting/install/linux.rst b/docs/starting/install/linux.rst
index 5032ed216..06aeb9ee8 100644
--- a/docs/starting/install/linux.rst
+++ b/docs/starting/install/linux.rst
@@ -58,7 +58,7 @@ project's directory
.. code-block:: console
- $ virtualenv venv
+ $ virtualenv --distribute venv
To use an environment, run ``source venv/bin/activate``. Your command prompt
will change to show the active environment. Once you have finished working in
From 80a12a70ff2795bc23712e28d38b5c185457343e Mon Sep 17 00:00:00 2001
From: Estevan Pequeno
Date: Thu, 5 Jul 2012 01:57:37 -0500
Subject: [PATCH 0031/1232] markup fix
---
docs/writing/structure.rst | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index 425458667..87d8c4383 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -96,8 +96,8 @@ will interfere with the way python looks for modules.
In this example python expects to find a "spam.py" file in a folder named "my"
which is not the case. There is an
-`example `_
- of how the dot should be used available in the python docs.
+`example `_ of how the
+dot should be used available in the python docs.
If you'd like you could name it as `my_spam.py` but even our friend the
underscore should not be seen often in module names.
From 9f792956db86c46bb2e6425889ebe6c6ce9fbfd0 Mon Sep 17 00:00:00 2001
From: Estevan Pequeno
Date: Thu, 5 Jul 2012 01:59:25 -0500
Subject: [PATCH 0032/1232] small edit
---
docs/writing/structure.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index 87d8c4383..cfd749c18 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -97,7 +97,7 @@ will interfere with the way python looks for modules.
In this example python expects to find a "spam.py" file in a folder named "my"
which is not the case. There is an
`example `_ of how the
-dot should be used available in the python docs.
+dot notation should be used in the python docs.
If you'd like you could name it as `my_spam.py` but even our friend the
underscore should not be seen often in module names.
From 0a045fdf78cf3da9f0791a62cacc8d971c979c2c Mon Sep 17 00:00:00 2001
From: Thomas Ballinger
Date: Thu, 5 Jul 2012 14:25:25 -0400
Subject: [PATCH 0033/1232] Fix spelling in style guide
---
docs/writing/style.rst | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index 462ffba0d..697e18c65 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -9,7 +9,7 @@ recognised fact that code is read much more often than it is written.
One reason for Python code to be easily read and understood is its relatively
complete set of Code Style guidelines and "Pythonic" idioms.
-Moreover, when a veteran Python developer (a Pythonistas) point to some
+Moreover, when a veteran Python developer (a Pythonista) point to some
parts of a code and say it is not "Pythonic", it usually means that these lines
of code do not follow the common guidelines and fail to express the intent in
what is considered the best (hear: most readable) way.
@@ -178,7 +178,7 @@ possibilities, because it grows the confidence that no hard-wall will be on the
way. However, knowing how to use them and particularly when **not** to use
them is the most important.
-Like a Kungfu master, a pythonistas knows how to kill with a single finger, and
+Like a Kungfu master, a Pythonista knows how to kill with a single finger, and
never do it.
We are all consenting adults
From a8e36af3eac37f9a1c7ad8e933165641bac47dae Mon Sep 17 00:00:00 2001
From: Thomas Ballinger
Date: Thu, 5 Jul 2012 14:47:47 -0400
Subject: [PATCH 0034/1232] fix grammar issues with style guide
---
docs/writing/style.rst | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index 697e18c65..5181b9ae1 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -128,7 +128,7 @@ called with each recipient as an argument: ``send('Hello', 'God', 'Mom',
'Cthulhu')``, and in the function body ``args`` will be equal to ``('God',
'Mom', 'Cthulhu')``.
-However, this construct has some drawback and should be used with caution. If a
+However, this construct has some drawbacks and should be used with caution. If a
function receives a list of arguments of the same nature, it is often more
clear to define it as a function of one argument, that argument being a list or
any sequence. Here, if ``send`` has multiple recipients, it is better to define
@@ -156,7 +156,7 @@ Python functions that are:
* easy to read (the name and arguments need no explanations)
-* easy to change (adding a new keyword argument do not break other parts of the
+* easy to change (adding a new keyword argument does not break other parts of the
code)
Avoid the magical wand
@@ -179,7 +179,7 @@ way. However, knowing how to use them and particularly when **not** to use
them is the most important.
Like a Kungfu master, a Pythonista knows how to kill with a single finger, and
-never do it.
+never to do it.
We are all consenting adults
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
From 96fb1d42d14e437dc164bc61aee166237cb8bd62 Mon Sep 17 00:00:00 2001
From: Thomas Ballinger
Date: Thu, 5 Jul 2012 14:41:21 -0400
Subject: [PATCH 0035/1232] remove slashes in code sample in style guide
---
docs/writing/style.rst | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index 462ffba0d..b8e2199dc 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -30,9 +30,9 @@ most explicit and straightforward manner is preferred.
.. code-block:: python
- def make_complex(\*args):
+ def make_complex(*args):
x, y = args
- return dict(\**locals())
+ return dict(**locals())
**Good**
From bbb1c2ea199d6f0f26b6292ebecb91cff59e218f Mon Sep 17 00:00:00 2001
From: Kenneth Reitz
Date: Sun, 8 Jul 2012 15:48:56 -0400
Subject: [PATCH 0036/1232] Revert "Fix spelling in structure.rst"
This reverts commit 0ff26166c62f78d3b911e90e17173d3b04d6b5d0.
---
docs/writing/structure.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index cfd749c18..3ac9cabae 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -306,7 +306,7 @@ clearer and thus preferred.
This mechanism is useful for separating concerns and avoiding
external un-related logic 'polluting' the core logic of the function
or method. A good example of a piece of functionality that is better handled
-with decoration is memorization or caching: you want to store the results of an
+with decoration is memoization or caching: you want to store the results of an
expensive function in a table and use them directly instead of recomputing
them when they have already been computed. This is clearly not part
of the function logic.
From 482e56c51ee69b27cc9d900eea7ec34ba4ec0221 Mon Sep 17 00:00:00 2001
From: Aaron Kavlie
Date: Mon, 16 Jul 2012 10:43:27 -0700
Subject: [PATCH 0037/1232] Add Mac OS X PIL installation instructions
---
docs/scenarios/imaging.rst | 18 ++++++++++++++++--
1 file changed, 16 insertions(+), 2 deletions(-)
diff --git a/docs/scenarios/imaging.rst b/docs/scenarios/imaging.rst
index d1a4c0cb6..6a5c01780 100644
--- a/docs/scenarios/imaging.rst
+++ b/docs/scenarios/imaging.rst
@@ -35,8 +35,22 @@ Ubuntu 11.04
Installing on Mac OS X
~~~~~~~~~~~~~~~~~~~~~~
-.. todo::
- Notes on installing on Mac OS X
+PIP doesn't know about the Mac OS X Freetype paths. To rectify that:
+
+.. code-block:: bash
+
+ $ ln -s /usr/X11/include/freetype2 /usr/local/include/
+ $ ln -s /usr/X11/include/ft2build.h /usr/local/include/
+ $ ln -s /usr/X11/lib/libfreetype.6.dylib /usr/local/lib/
+ $ ln -s /usr/X11/lib/libfreetype.6.dylib /usr/local/lib/libfreetype.dylib
+
+then:
+
+.. code-block:: bash
+
+ $ brew install libjpeg
+ $ pip install PIL
+
Installing on Windows
~~~~~~~~~~~~~~~~~~~~~
From ccea69feb0009e56d7d70e6068ff2f68f328c65e Mon Sep 17 00:00:00 2001
From: Kenneth Reitz
Date: Mon, 16 Jul 2012 20:59:54 -0400
Subject: [PATCH 0038/1232] hmm
---
requirements.txt | 1 +
1 file changed, 1 insertion(+)
create mode 100644 requirements.txt
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 000000000..663bd1f6a
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1 @@
+requests
\ No newline at end of file
From 33ab7535c27ae79bbb07372e214203f673fd2e86 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Domen=20Ko=C5=BEar?=
Date: Wed, 25 Jul 2012 22:47:26 +0200
Subject: [PATCH 0039/1232] Add comparison table and py2exe notes on freezing
topic
---
docs/shipping/freezing.rst | 82 ++++++++++++++++++++++++++++++++------
1 file changed, 70 insertions(+), 12 deletions(-)
diff --git a/docs/shipping/freezing.rst b/docs/shipping/freezing.rst
index b6803af31..fc46cddff 100644
--- a/docs/shipping/freezing.rst
+++ b/docs/shipping/freezing.rst
@@ -8,42 +8,100 @@ Many applications you use every day do this:
- Dropbox
- BitTorrent
--
-
+- ...
.. todo:: Fill in "Freezing Your Code" stub
+
+
+Comparison
+----------
+
+Solutions and platforms/features supported:
+
+=========== ======= ===== ==== ======== ======= ============= ============== ==== =====================
+Solution Windows Linux OS X Python 3 Licence One-file mode Zipfile import Eggs pkg_resources support
+=========== ======= ===== ==== ======== ======= ============= ============== ==== =====================
+bbFreeze yes yes yes no MIT no yes yes yes
+py2exe yes no no no MIT yes yes no no
+pyInstaller yes yes yes no GPL yes no yes no
+cx_Freeze yes yes yes yes PSF no yes yes no
+=========== ======= ===== ==== ======== ======= ============= ============== ==== =====================
+
+.. todo:: Add other solutions: py2app
+
+.. note::
+ Freezing Python code on Linux into a Windows executable was only once
+ supported in PyInstaller, `but later dropped
+ `_.
+
+.. note::
+ All solutions need MS Visual C++ dll to be installed on target machine.
+ Only Pyinstaller makes self-executable exe that bundles the dll when
+ passing ``--onefile`` to `Configure.py`.
+
Windows
-:::::::
+-------
+
+bbFreeze
+~~~~~~~~
+
+Prerequisite is to install :ref:`Python, Distribute and pywin32 dependency on Windows `.
+.. todo:: Write steps for most basic .exe
py2exe
-------
+~~~~~~
+Prerequisite is to install :ref:`Python on Windows `.
+1. Download and install http://sourceforge.net/projects/py2exe/files/py2exe/
-OSX
-:::
+2. Write setup.py (`List of configuration options `_)::
+ from distutils.core import setup
+ import py2exe
-py2app
-------
+ setup(
+ windows=[{'script': 'foobar.py'}],
+ )
+
+3. (Optionally) `include icon `_
+4. (Optionally) `one-file mode `_
+5. Generate `.exe` into `dist` directory::
+ $ python setup.py py2exe
+
+6. Provide the Microsoft Visual C runtime DLL. Two options: `globally install dll on target machine `_ or `distribute dll aloneside with .exe `_.
PyInstaller
------------
+~~~~~~~~~~~
+
+Prerequisite is to have installed :ref:`Python, Distribute and pywin32 dependency on Windows `.
+
+- `Most basic tutorial `_
+- `Manual `_
+OSX
+---
+
+
+py2app
+~~~~~~
+
+PyInstaller
+~~~~~~~~~~~
Linux
-:::::
+-----
bbFreeze
---------
+~~~~~~~~
PyInstaller
------------
+~~~~~~~~~~~
From 291c0ff37ace2045a2b3b9d8eda9e05a8e157b0a Mon Sep 17 00:00:00 2001
From: Dan Crosta
Date: Sat, 28 Jul 2012 13:28:37 -0400
Subject: [PATCH 0040/1232] make targets in docs/Makefile available at top
level
---
Makefile | 9 +++++++--
1 file changed, 7 insertions(+), 2 deletions(-)
diff --git a/Makefile b/Makefile
index 4c2b0cf39..e702e7819 100644
--- a/Makefile
+++ b/Makefile
@@ -1,2 +1,7 @@
-build:
- cd docs && make html
\ No newline at end of file
+.PHONY: build
+build: html
+
+# this pattern rule lets you run "make build" (or any other target
+# in docs/Makefile) in this directory as though you were in docs/
+%:
+ cd docs && make $@
From 49b5ccba95f1c56e7585cef9e473eeb4171f4f4e Mon Sep 17 00:00:00 2001
From: Kenneth Reitz
Date: Sat, 28 Jul 2012 17:11:13 -0400
Subject: [PATCH 0041/1232] gittip
---
docs/_templates/sidebarintro.html | 10 ++++++++++
docs/_templates/sidebarlogo.html | 10 ++++++++++
2 files changed, 20 insertions(+)
diff --git a/docs/_templates/sidebarintro.html b/docs/_templates/sidebarintro.html
index 7ea44d915..b9901b381 100644
--- a/docs/_templates/sidebarintro.html
+++ b/docs/_templates/sidebarintro.html
@@ -3,6 +3,16 @@ Python Guide.
This opinionated guide exists to provide both novice and expert Python developers a best-practice handbook to the installation, configuration, and usage of Python on a daily basis.
+Donate
+
+ If you enjoy this guide, consider supporting the author on Gittip:
+
+
+
+
+
Feedback
Feedback is greatly appreciated. If you have any questions, comments,
diff --git a/docs/_templates/sidebarlogo.html b/docs/_templates/sidebarlogo.html
index a39cee9b2..d7f12de20 100644
--- a/docs/_templates/sidebarlogo.html
+++ b/docs/_templates/sidebarlogo.html
@@ -2,3 +2,13 @@
This opinionated guide exists to provide both novice and expert Python developers a best-practice handbook to the installation, configuration, and usage of Python on a daily basis.
+
+Donate
+
+ If you enjoy this guide, consider supporting the author on Gittip:
+
+
+
+
\ No newline at end of file
From d6602f18b69224f8d1b405dd36d1ef121b1941c7 Mon Sep 17 00:00:00 2001
From: Lyndsy Simon
Date: Wed, 1 Aug 2012 20:01:05 -0500
Subject: [PATCH 0042/1232] removes link to Sublime Text 2 Beta (now released)
---
docs/dev/env.rst | 3 ---
1 file changed, 3 deletions(-)
diff --git a/docs/dev/env.rst b/docs/dev/env.rst
index a539a9fe4..a47de462c 100644
--- a/docs/dev/env.rst
+++ b/docs/dev/env.rst
@@ -89,9 +89,6 @@ extraordinary features."
Sublime Text has excellent support for editing Python code and uses Python for
its plugin API.
-`Sublime Text 2 `_
-is currently in beta.
-
IDEs
::::
From 22088fd0a419a32102c6be197a286064195a7245 Mon Sep 17 00:00:00 2001
From: Kirill Klenov
Date: Thu, 2 Aug 2012 23:59:41 +0400
Subject: [PATCH 0043/1232] Added information about vim python-mode plugin
---
docs/dev/env.rst | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)
diff --git a/docs/dev/env.rst b/docs/dev/env.rst
index a47de462c..88dd0d22f 100644
--- a/docs/dev/env.rst
+++ b/docs/dev/env.rst
@@ -60,6 +60,24 @@ to do that which also shows status and warning messages in the statusbar would b
let g:syntastic_auto_loc_list=1
let g:syntastic_loc_list_height=5
+Python-mode
+^^^^^^^^^^^
+
+Python-mode_ is complex solution in VIM for work with python code.
+It's have:
+
+- Async python code checking (pylint, pyflakes, pep8, mccabe) in any combination;
+- Code refactoring and autocompletion with Rope;
+- Fastest python folding;
+- Nice and powered python syntax;
+- Virtual env support;
+- Search by python documentation and run python code;
+- More other things like auto pep8 error fixes;
+- Very customizable an documented as well;
+- Have all required libraries in self;
+
+And more stuff.
+
.. _indent: http://www.vim.org/scripts/script.php?script_id=974
.. _syntax: http://www.vim.org/scripts/script.php?script_id=790
@@ -68,6 +86,7 @@ to do that which also shows status and warning messages in the statusbar would b
.. _PEP8: http://pypi.python.org/pypi/pep8/
.. _vim-pep8: https://github.com/nvie/vim-pep8
.. _syntastic: https://github.com/scrooloose/syntastic
+.. _Python-mode: https://github.com/klen/python-mode
.. todo:: add supertab notes
From 97c1cbc4004f0fd31c314c93480ec43913049d78 Mon Sep 17 00:00:00 2001
From: Kenneth Reitz
Date: Mon, 3 Sep 2012 04:06:10 -0400
Subject: [PATCH 0044/1232] lawyer up
---
LICENSE | 360 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 360 insertions(+)
create mode 100644 LICENSE
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 000000000..a632f3e73
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,360 @@
+Creative Commons Legal Code
+
+Attribution-NonCommercial-ShareAlike 3.0 Unported
+
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
+ LEGAL SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
+ REGARDING THE INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR
+ DAMAGES RESULTING FROM ITS USE.
+
+License
+
+THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE
+COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY
+COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS
+AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
+
+BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE
+TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY
+BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS
+CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND
+CONDITIONS.
+
+1. Definitions
+
+ a. "Adaptation" means a work based upon the Work, or upon the Work and
+ other pre-existing works, such as a translation, adaptation,
+ derivative work, arrangement of music or other alterations of a
+ literary or artistic work, or phonogram or performance and includes
+ cinematographic adaptations or any other form in which the Work may be
+ recast, transformed, or adapted including in any form recognizably
+ derived from the original, except that a work that constitutes a
+ Collection will not be considered an Adaptation for the purpose of
+ this License. For the avoidance of doubt, where the Work is a musical
+ work, performance or phonogram, the synchronization of the Work in
+ timed-relation with a moving image ("synching") will be considered an
+ Adaptation for the purpose of this License.
+ b. "Collection" means a collection of literary or artistic works, such as
+ encyclopedias and anthologies, or performances, phonograms or
+ broadcasts, or other works or subject matter other than works listed
+ in Section 1(g) below, which, by reason of the selection and
+ arrangement of their contents, constitute intellectual creations, in
+ which the Work is included in its entirety in unmodified form along
+ with one or more other contributions, each constituting separate and
+ independent works in themselves, which together are assembled into a
+ collective whole. A work that constitutes a Collection will not be
+ considered an Adaptation (as defined above) for the purposes of this
+ License.
+ c. "Distribute" means to make available to the public the original and
+ copies of the Work or Adaptation, as appropriate, through sale or
+ other transfer of ownership.
+ d. "License Elements" means the following high-level license attributes
+ as selected by Licensor and indicated in the title of this License:
+ Attribution, Noncommercial, ShareAlike.
+ e. "Licensor" means the individual, individuals, entity or entities that
+ offer(s) the Work under the terms of this License.
+ f. "Original Author" means, in the case of a literary or artistic work,
+ the individual, individuals, entity or entities who created the Work
+ or if no individual or entity can be identified, the publisher; and in
+ addition (i) in the case of a performance the actors, singers,
+ musicians, dancers, and other persons who act, sing, deliver, declaim,
+ play in, interpret or otherwise perform literary or artistic works or
+ expressions of folklore; (ii) in the case of a phonogram the producer
+ being the person or legal entity who first fixes the sounds of a
+ performance or other sounds; and, (iii) in the case of broadcasts, the
+ organization that transmits the broadcast.
+ g. "Work" means the literary and/or artistic work offered under the terms
+ of this License including without limitation any production in the
+ literary, scientific and artistic domain, whatever may be the mode or
+ form of its expression including digital form, such as a book,
+ pamphlet and other writing; a lecture, address, sermon or other work
+ of the same nature; a dramatic or dramatico-musical work; a
+ choreographic work or entertainment in dumb show; a musical
+ composition with or without words; a cinematographic work to which are
+ assimilated works expressed by a process analogous to cinematography;
+ a work of drawing, painting, architecture, sculpture, engraving or
+ lithography; a photographic work to which are assimilated works
+ expressed by a process analogous to photography; a work of applied
+ art; an illustration, map, plan, sketch or three-dimensional work
+ relative to geography, topography, architecture or science; a
+ performance; a broadcast; a phonogram; a compilation of data to the
+ extent it is protected as a copyrightable work; or a work performed by
+ a variety or circus performer to the extent it is not otherwise
+ considered a literary or artistic work.
+ h. "You" means an individual or entity exercising rights under this
+ License who has not previously violated the terms of this License with
+ respect to the Work, or who has received express permission from the
+ Licensor to exercise rights under this License despite a previous
+ violation.
+ i. "Publicly Perform" means to perform public recitations of the Work and
+ to communicate to the public those public recitations, by any means or
+ process, including by wire or wireless means or public digital
+ performances; to make available to the public Works in such a way that
+ members of the public may access these Works from a place and at a
+ place individually chosen by them; to perform the Work to the public
+ by any means or process and the communication to the public of the
+ performances of the Work, including by public digital performance; to
+ broadcast and rebroadcast the Work by any means including signs,
+ sounds or images.
+ j. "Reproduce" means to make copies of the Work by any means including
+ without limitation by sound or visual recordings and the right of
+ fixation and reproducing fixations of the Work, including storage of a
+ protected performance or phonogram in digital form or other electronic
+ medium.
+
+2. Fair Dealing Rights. Nothing in this License is intended to reduce,
+limit, or restrict any uses free from copyright or rights arising from
+limitations or exceptions that are provided for in connection with the
+copyright protection under copyright law or other applicable laws.
+
+3. License Grant. Subject to the terms and conditions of this License,
+Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
+perpetual (for the duration of the applicable copyright) license to
+exercise the rights in the Work as stated below:
+
+ a. to Reproduce the Work, to incorporate the Work into one or more
+ Collections, and to Reproduce the Work as incorporated in the
+ Collections;
+ b. to create and Reproduce Adaptations provided that any such Adaptation,
+ including any translation in any medium, takes reasonable steps to
+ clearly label, demarcate or otherwise identify that changes were made
+ to the original Work. For example, a translation could be marked "The
+ original work was translated from English to Spanish," or a
+ modification could indicate "The original work has been modified.";
+ c. to Distribute and Publicly Perform the Work including as incorporated
+ in Collections; and,
+ d. to Distribute and Publicly Perform Adaptations.
+
+The above rights may be exercised in all media and formats whether now
+known or hereafter devised. The above rights include the right to make
+such modifications as are technically necessary to exercise the rights in
+other media and formats. Subject to Section 8(f), all rights not expressly
+granted by Licensor are hereby reserved, including but not limited to the
+rights described in Section 4(e).
+
+4. Restrictions. The license granted in Section 3 above is expressly made
+subject to and limited by the following restrictions:
+
+ a. You may Distribute or Publicly Perform the Work only under the terms
+ of this License. You must include a copy of, or the Uniform Resource
+ Identifier (URI) for, this License with every copy of the Work You
+ Distribute or Publicly Perform. You may not offer or impose any terms
+ on the Work that restrict the terms of this License or the ability of
+ the recipient of the Work to exercise the rights granted to that
+ recipient under the terms of the License. You may not sublicense the
+ Work. You must keep intact all notices that refer to this License and
+ to the disclaimer of warranties with every copy of the Work You
+ Distribute or Publicly Perform. When You Distribute or Publicly
+ Perform the Work, You may not impose any effective technological
+ measures on the Work that restrict the ability of a recipient of the
+ Work from You to exercise the rights granted to that recipient under
+ the terms of the License. This Section 4(a) applies to the Work as
+ incorporated in a Collection, but this does not require the Collection
+ apart from the Work itself to be made subject to the terms of this
+ License. If You create a Collection, upon notice from any Licensor You
+ must, to the extent practicable, remove from the Collection any credit
+ as required by Section 4(d), as requested. If You create an
+ Adaptation, upon notice from any Licensor You must, to the extent
+ practicable, remove from the Adaptation any credit as required by
+ Section 4(d), as requested.
+ b. You may Distribute or Publicly Perform an Adaptation only under: (i)
+ the terms of this License; (ii) a later version of this License with
+ the same License Elements as this License; (iii) a Creative Commons
+ jurisdiction license (either this or a later license version) that
+ contains the same License Elements as this License (e.g.,
+ Attribution-NonCommercial-ShareAlike 3.0 US) ("Applicable License").
+ You must include a copy of, or the URI, for Applicable License with
+ every copy of each Adaptation You Distribute or Publicly Perform. You
+ may not offer or impose any terms on the Adaptation that restrict the
+ terms of the Applicable License or the ability of the recipient of the
+ Adaptation to exercise the rights granted to that recipient under the
+ terms of the Applicable License. You must keep intact all notices that
+ refer to the Applicable License and to the disclaimer of warranties
+ with every copy of the Work as included in the Adaptation You
+ Distribute or Publicly Perform. When You Distribute or Publicly
+ Perform the Adaptation, You may not impose any effective technological
+ measures on the Adaptation that restrict the ability of a recipient of
+ the Adaptation from You to exercise the rights granted to that
+ recipient under the terms of the Applicable License. This Section 4(b)
+ applies to the Adaptation as incorporated in a Collection, but this
+ does not require the Collection apart from the Adaptation itself to be
+ made subject to the terms of the Applicable License.
+ c. You may not exercise any of the rights granted to You in Section 3
+ above in any manner that is primarily intended for or directed toward
+ commercial advantage or private monetary compensation. The exchange of
+ the Work for other copyrighted works by means of digital file-sharing
+ or otherwise shall not be considered to be intended for or directed
+ toward commercial advantage or private monetary compensation, provided
+ there is no payment of any monetary compensation in con-nection with
+ the exchange of copyrighted works.
+ d. If You Distribute, or Publicly Perform the Work or any Adaptations or
+ Collections, You must, unless a request has been made pursuant to
+ Section 4(a), keep intact all copyright notices for the Work and
+ provide, reasonable to the medium or means You are utilizing: (i) the
+ name of the Original Author (or pseudonym, if applicable) if supplied,
+ and/or if the Original Author and/or Licensor designate another party
+ or parties (e.g., a sponsor institute, publishing entity, journal) for
+ attribution ("Attribution Parties") in Licensor's copyright notice,
+ terms of service or by other reasonable means, the name of such party
+ or parties; (ii) the title of the Work if supplied; (iii) to the
+ extent reasonably practicable, the URI, if any, that Licensor
+ specifies to be associated with the Work, unless such URI does not
+ refer to the copyright notice or licensing information for the Work;
+ and, (iv) consistent with Section 3(b), in the case of an Adaptation,
+ a credit identifying the use of the Work in the Adaptation (e.g.,
+ "French translation of the Work by Original Author," or "Screenplay
+ based on original Work by Original Author"). The credit required by
+ this Section 4(d) may be implemented in any reasonable manner;
+ provided, however, that in the case of a Adaptation or Collection, at
+ a minimum such credit will appear, if a credit for all contributing
+ authors of the Adaptation or Collection appears, then as part of these
+ credits and in a manner at least as prominent as the credits for the
+ other contributing authors. For the avoidance of doubt, You may only
+ use the credit required by this Section for the purpose of attribution
+ in the manner set out above and, by exercising Your rights under this
+ License, You may not implicitly or explicitly assert or imply any
+ connection with, sponsorship or endorsement by the Original Author,
+ Licensor and/or Attribution Parties, as appropriate, of You or Your
+ use of the Work, without the separate, express prior written
+ permission of the Original Author, Licensor and/or Attribution
+ Parties.
+ e. For the avoidance of doubt:
+
+ i. Non-waivable Compulsory License Schemes. In those jurisdictions in
+ which the right to collect royalties through any statutory or
+ compulsory licensing scheme cannot be waived, the Licensor
+ reserves the exclusive right to collect such royalties for any
+ exercise by You of the rights granted under this License;
+ ii. Waivable Compulsory License Schemes. In those jurisdictions in
+ which the right to collect royalties through any statutory or
+ compulsory licensing scheme can be waived, the Licensor reserves
+ the exclusive right to collect such royalties for any exercise by
+ You of the rights granted under this License if Your exercise of
+ such rights is for a purpose or use which is otherwise than
+ noncommercial as permitted under Section 4(c) and otherwise waives
+ the right to collect royalties through any statutory or compulsory
+ licensing scheme; and,
+ iii. Voluntary License Schemes. The Licensor reserves the right to
+ collect royalties, whether individually or, in the event that the
+ Licensor is a member of a collecting society that administers
+ voluntary licensing schemes, via that society, from any exercise
+ by You of the rights granted under this License that is for a
+ purpose or use which is otherwise than noncommercial as permitted
+ under Section 4(c).
+ f. Except as otherwise agreed in writing by the Licensor or as may be
+ otherwise permitted by applicable law, if You Reproduce, Distribute or
+ Publicly Perform the Work either by itself or as part of any
+ Adaptations or Collections, You must not distort, mutilate, modify or
+ take other derogatory action in relation to the Work which would be
+ prejudicial to the Original Author's honor or reputation. Licensor
+ agrees that in those jurisdictions (e.g. Japan), in which any exercise
+ of the right granted in Section 3(b) of this License (the right to
+ make Adaptations) would be deemed to be a distortion, mutilation,
+ modification or other derogatory action prejudicial to the Original
+ Author's honor and reputation, the Licensor will waive or not assert,
+ as appropriate, this Section, to the fullest extent permitted by the
+ applicable national law, to enable You to reasonably exercise Your
+ right under Section 3(b) of this License (right to make Adaptations)
+ but not otherwise.
+
+5. Representations, Warranties and Disclaimer
+
+UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING AND TO THE
+FULLEST EXTENT PERMITTED BY APPLICABLE LAW, LICENSOR OFFERS THE WORK AS-IS
+AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE
+WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT
+LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
+PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS,
+ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT
+DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED
+WARRANTIES, SO THIS EXCLUSION MAY NOT APPLY TO YOU.
+
+6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE
+LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR
+ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES
+ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS
+BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+7. Termination
+
+ a. This License and the rights granted hereunder will terminate
+ automatically upon any breach by You of the terms of this License.
+ Individuals or entities who have received Adaptations or Collections
+ from You under this License, however, will not have their licenses
+ terminated provided such individuals or entities remain in full
+ compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will
+ survive any termination of this License.
+ b. Subject to the above terms and conditions, the license granted here is
+ perpetual (for the duration of the applicable copyright in the Work).
+ Notwithstanding the above, Licensor reserves the right to release the
+ Work under different license terms or to stop distributing the Work at
+ any time; provided, however that any such election will not serve to
+ withdraw this License (or any other license that has been, or is
+ required to be, granted under the terms of this License), and this
+ License will continue in full force and effect unless terminated as
+ stated above.
+
+8. Miscellaneous
+
+ a. Each time You Distribute or Publicly Perform the Work or a Collection,
+ the Licensor offers to the recipient a license to the Work on the same
+ terms and conditions as the license granted to You under this License.
+ b. Each time You Distribute or Publicly Perform an Adaptation, Licensor
+ offers to the recipient a license to the original Work on the same
+ terms and conditions as the license granted to You under this License.
+ c. If any provision of this License is invalid or unenforceable under
+ applicable law, it shall not affect the validity or enforceability of
+ the remainder of the terms of this License, and without further action
+ by the parties to this agreement, such provision shall be reformed to
+ the minimum extent necessary to make such provision valid and
+ enforceable.
+ d. No term or provision of this License shall be deemed waived and no
+ breach consented to unless such waiver or consent shall be in writing
+ and signed by the party to be charged with such waiver or consent.
+ e. This License constitutes the entire agreement between the parties with
+ respect to the Work licensed here. There are no understandings,
+ agreements or representations with respect to the Work not specified
+ here. Licensor shall not be bound by any additional provisions that
+ may appear in any communication from You. This License may not be
+ modified without the mutual written agreement of the Licensor and You.
+ f. The rights granted under, and the subject matter referenced, in this
+ License were drafted utilizing the terminology of the Berne Convention
+ for the Protection of Literary and Artistic Works (as amended on
+ September 28, 1979), the Rome Convention of 1961, the WIPO Copyright
+ Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996
+ and the Universal Copyright Convention (as revised on July 24, 1971).
+ These rights and subject matter take effect in the relevant
+ jurisdiction in which the License terms are sought to be enforced
+ according to the corresponding provisions of the implementation of
+ those treaty provisions in the applicable national law. If the
+ standard suite of rights granted under applicable copyright law
+ includes additional rights not granted under this License, such
+ additional rights are deemed to be included in the License; this
+ License is not intended to restrict the license of any rights under
+ applicable law.
+
+
+Creative Commons Notice
+
+ Creative Commons is not a party to this License, and makes no warranty
+ whatsoever in connection with the Work. Creative Commons will not be
+ liable to You or any party on any legal theory for any damages
+ whatsoever, including without limitation any general, special,
+ incidental or consequential damages arising in connection to this
+ license. Notwithstanding the foregoing two (2) sentences, if Creative
+ Commons has expressly identified itself as the Licensor hereunder, it
+ shall have all rights and obligations of Licensor.
+
+ Except for the limited purpose of indicating to the public that the
+ Work is licensed under the CCPL, Creative Commons does not authorize
+ the use by either party of the trademark "Creative Commons" or any
+ related trademark or logo of Creative Commons without the prior
+ written consent of Creative Commons. Any permitted use will be in
+ compliance with Creative Commons' then-current trademark usage
+ guidelines, as may be published on its website or otherwise made
+ available upon request from time to time. For the avoidance of doubt,
+ this trademark restriction does not form part of this License.
+
+ Creative Commons may be contacted at http://creativecommons.org/.
From 281a37ed06ea5b2f938fae46d2b26df2c4422aaf Mon Sep 17 00:00:00 2001
From: David Fischer
Date: Fri, 7 Sep 2012 10:44:37 -0400
Subject: [PATCH 0045/1232] Added notes about getting Python2.6 on RHEL/CentOS
---
docs/starting/install/linux.rst | 12 +++++++++++-
1 file changed, 11 insertions(+), 1 deletion(-)
diff --git a/docs/starting/install/linux.rst b/docs/starting/install/linux.rst
index 06aeb9ee8..1fd04cba4 100644
--- a/docs/starting/install/linux.rst
+++ b/docs/starting/install/linux.rst
@@ -3,7 +3,17 @@
Installing Python on Linux
==========================
-The latest version of Ubuntu, **comes with Python 2.7 out of the box**.
+The latest versions of Ubuntu and Fedora **come with Python 2.7 out of the box**.
+
+The latest versions of Redhat Enterprise (RHEL) and CentOS come with Python 2.6.
+Some older versions of RHEL and CentOS come with Python 2.4 which is
+unacceptable for modern Python development. Fortunately, there are
+`Extra Packages for Enterprise Linux`_ which include high
+quality additional packages based on their Fedora counterparts. This
+repository contains a Python 2.6 package specifically designed to install
+side-by-side with the system's Python 2.4 installation.
+
+.. _Extra Packages for Enterprise Linux: http://fedoraproject.org/wiki/EPEL
You do not need to install or configure anything else to use Python. Having
said that, I would strongly recommend that you install the tools and libraries
From f2ca4ea7c6ba46d30bdf5b3987889bfa0bdba9ed Mon Sep 17 00:00:00 2001
From: silkuze
Date: Sat, 8 Sep 2012 15:23:39 +0300
Subject: [PATCH 0046/1232] Missing a semicolon in the function definition
---
docs/writing/structure.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index 3ac9cabae..35dd43254 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -347,7 +347,7 @@ Some guidelines help to avoid this issue:
count = 1
msg = 'a string'
- def func()
+ def func():
pass # Do something
Using short functions or methods helps reduce the risk
From 632f8ae4e772e30ddf46fd58915bd26d9d7df5b7 Mon Sep 17 00:00:00 2001
From: Alex Hoffman
Date: Tue, 11 Sep 2012 14:09:22 +1000
Subject: [PATCH 0047/1232] Updated IronPython link to latest stable 2.7.3
---
docs/starting/which-python.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/starting/which-python.rst b/docs/starting/which-python.rst
index 9c6e32f71..af72adba7 100644
--- a/docs/starting/which-python.rst
+++ b/docs/starting/which-python.rst
@@ -102,4 +102,4 @@ IronPython supports Python 2.7. [#iron_ver]_
.. [#jython_ver] http://wiki.python.org/jython/JythonFaq/GeneralInfo#Is_Jython_the_same_language_as_Python.3F
-.. [#iron_ver] http://ironpython.codeplex.com/releases/view/54498
\ No newline at end of file
+.. [#iron_ver] http://ironpython.codeplex.com/releases/view/81726
From b96b11fe59d6fd761f0a96a34c968f29bbff0cf9 Mon Sep 17 00:00:00 2001
From: Roger Barnes
Date: Tue, 18 Sep 2012 21:04:14 +1000
Subject: [PATCH 0048/1232] Add mock library to testing page
---
docs/writing/tests.rst | 16 +++++++++++++++-
1 file changed, 15 insertions(+), 1 deletion(-)
diff --git a/docs/writing/tests.rst b/docs/writing/tests.rst
index 12590b6f5..342b13383 100644
--- a/docs/writing/tests.rst
+++ b/docs/writing/tests.rst
@@ -1,5 +1,5 @@
Testing Your Code
-=====================
+=================
Testing your code is very important.
@@ -248,3 +248,17 @@ the need to change any other code.
`unittest2 `_
+mock
+----
+
+mock is a library for testing in Python.
+
+::
+
+ $ pip install mock
+
+It allows you to replace parts of your system under test with mock objects and
+make assertions about how they have been used.
+
+ `mock `_
+
From 3b902fe0906ea25816ab5171f9e8776472b0f213 Mon Sep 17 00:00:00 2001
From: Roger Barnes
Date: Wed, 19 Sep 2012 16:46:54 +1000
Subject: [PATCH 0049/1232] Add examples to section on mock
---
docs/writing/tests.rst | 32 ++++++++++++++++++++++++++++++++
1 file changed, 32 insertions(+)
diff --git a/docs/writing/tests.rst b/docs/writing/tests.rst
index 342b13383..975adf67b 100644
--- a/docs/writing/tests.rst
+++ b/docs/writing/tests.rst
@@ -260,5 +260,37 @@ mock is a library for testing in Python.
It allows you to replace parts of your system under test with mock objects and
make assertions about how they have been used.
+For example, you can monkey patch a method
+
+::
+
+ from mock import MagicMock
+ thing = ProductionClass()
+ thing.method = MagicMock(return_value=3)
+ thing.method(3, 4, 5, key='value')
+
+ thing.method.assert_called_with(3, 4, 5, key='value')
+
+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
+always returns the same result (but only for the duration of the test).
+
+::
+
+ def mock_search(self):
+ class MockSearchQuerySet(SearchQuerySet):
+ def __iter__(self):
+ return iter(["foo", "bar", "baz"])
+ return MockSearchQuerySet()
+
+ # SearchForm here refers to the imported class reference in myapp,
+ # not where the SearchForm class itself is imported from
+ @mock.patch('myapp.SearchForm.search', mock_search)
+ def test_new_watchlist_activities(self):
+ # get_search_results runs a search and iterates over the result
+ self.assertEqual(len(myapp.get_search_results(q="fish")), 3)
+
+Mock has many other ways you can configure it and control its behaviour.
+
`mock `_
From 29af1a209737615dbe497db6cb4c125b803ac409 Mon Sep 17 00:00:00 2001
From: Clint Howarth
Date: Sat, 22 Sep 2012 08:19:00 -0400
Subject: [PATCH 0050/1232] tighten, de-dup PEP8 content, improve
formatting/organization
---
docs/writing/documentation.rst | 339 +++++++++++++--------------------
1 file changed, 129 insertions(+), 210 deletions(-)
diff --git a/docs/writing/documentation.rst b/docs/writing/documentation.rst
index a598d4306..d61da5166 100644
--- a/docs/writing/documentation.rst
+++ b/docs/writing/documentation.rst
@@ -1,247 +1,166 @@
-Documenting Your Code
-=====================
-
-With readability of the code being a main focus for Python developers, proper
-commenting is naturally important. Some best practice apply to code comments
-and project documents, depending on the scope of the project.
-
-Project documents
------------------
-
-A README file at the root directory give general information to the users and
-the maintainers. It should be raw text or written in some very easy to read
-markup, such as reStructuredText and Markdown. It should contain a few lines
-explaining the purpose of the project or the library (without assuming the user
-knows anything about the project), the url of the main source for the software,
-and some basic credit information. This file is the main entry point for
-readers of the code.
-
-An INSTALL file is less often necessary with python, except if the dependencies
-are complex or unusual, or if some C modules need to be compiled before use.
-The installation instructions are often reduced to one command, such as ``pip
-install module`` or ``python setup.py install`` and added to the README file.
-
-A LICENSE file should always be present and specify the license under which the
+Documentation
+=============
+
+Readability is a primary focus for Python developers, in both project
+and code documentation. Following some simple best practices can save
+both you and others a lot of time.
+
+Project Documentation
+---------------------
+
+A ``README`` file at the root directory should give general
+information to the users and the maintainers. It should be raw text or
+written in some very easy to read markup, such as
+:ref:`reStructuredText-ref` and Markdown. It should contain a few
+lines explaining the purpose of the project or the library (without
+assuming the user knows anything about the project), the url of the
+main source for the software, and some basic credit information. This
+file is the main entry point for readers of the code.
+
+An ``INSTALL`` file is less necessary with python. The installation
+instructions are often reduced to one command, such as ``pip install
+module`` or ``python setup.py install`` and added to the ``README``
+file.
+
+A ``LICENSE`` file should *always* be present and specify the license under which the
software is made available to the public.
-A TODO file or a TODO section in README should list the planned modifications
-of the code.
+A ``TODO`` file or a ``TODO`` section in ``README`` should list the
+planned development for the code.
-A CHANGELOG file or section in README should compile a short overview of the
-changes in the code base for the latest versions.
+A ``CHANGELOG`` file or section in ``README`` should compile a short
+overview of the changes in the code base for the latest versions.
-Documentation
--------------
-
-As the project or library reaches a certain level of complexity, it may require
-a fuller documentation, which can be of different flavors:
-
-The introduction may show a very short overview of what can be done with the
-product, using one or two extremely simplified use cases.
-
-The tutorials will show in more details some main use cases. The reader will
-follow a step-by-step procedure to set-up a working prototype.
+Project Publication
+-------------------
-The API reference, which is often generated automatically from the code, will
-list all publicly available interfaces, their parameters and their return
-values, with an explanation of their use.
+Depending on the project, your documentation might include some or all
+of the following components:
-Some documents intended for developers might give guidance about code
-convention and general design decision of the project.
+- A *introduction* should show a very short overview of what can be
+ done with the product, using one or two extremely simplified use
+ cases. This is the thirty-second pitch for your project.
-Comments
---------
+- A *tutorial* should show some primary use cases in more detail. The reader will
+ follow a step-by-step procedure to set-up a working prototype.
-Comments are written directly inside the code, either using the hash sign (#)
-or a docstring_.
-
-.. _docstring: docstrings_
+- An *API reference* is typically generated from the code (see
+ :ref:`docstrings `). It will list all publicly available interfaces,
+ parameters, and return values.
-Finding the correct balance between undocumented code and verbose and useless
-comment boilerplates is difficult, and is the subject of heated discussion
-among developers.
+- *Developer documentation* is intended for potential contributors. This can
+ include code convention and general design strategy of the project.
-The following guidelines seem to be most commonly agreed upon:
-
-**Wrong or outdated comments are worse than no comments at all.** Following the
-saying that it is better, on a boat, to know that we do not know were we are
-than to wrongly believe we know where we are, wrong or outdated comments can be
-misleading for the maintainers, slow down considerably bug hunting or
-refactoring, and then, when discovered wrong, they will throw suspicion on all
-other comments in the code, regardless of their individual correctness.
-
-**There's no need to comment perfect code...** An hypothetical perfectly readable
-code, with a crystal clear logic stream, expressive variable and function
-names, orthogonal segmentation passing exactly between the flesh and the bones,
-and no implicit assumptions of any kind, would not require any comment at all.
-When striving for coding excellence, it is useful to see any existing comment,
-or any feeling of a need for a comment, as the sign that the code do not
-express clearly enough its intent and can be improved.
-
-**.. but no code is perfect.** Perfect code is a chimera, it exists only in
-our dreams. In real life, a code base is full of trade offs, and comments are
-often needed in the most difficult parts. Moreover, any special case, any
-obscure hack, any monkey patch and any ugly workaround MUST be signaled and
-explained by a proper comment. This should be enforced by the law!
-
-**TODOs** are special comments that a developer write as a reminder for later
-use. It is said that its original intent was that someone might, one day,
-search for the string "TODO" in the code base and actually roll their sleeves
-and start *to do the TODOs*. There is no available record that it ever
-happened. However, TODOs comment are still very useful, because they mark the
-current limits of the code, and it is not unlikely that, when required to add a
-new behavior to the actual code, looking at the TODOs will show where to start.
-
-**Do not use triple-quote strings to comment code.** A common operation when
-modifying code is to comment out some lines or even a full function or class
-definition. This can be done by adding triple-quotes around the code block to
-be skipped, but this is not a good practice, because line-oriented command-line
-tools such as ``grep`` will not be aware that the commented code is inactive.
-It is better to add hashes at the proper indentation level for every commented
-line. Good editors allow to do this with few keystrokes (ctrl-v on Vim).
-
-**Bad**
-
-.. code-block:: python
-
- def tricky_function():
- '''
- Commented out because its breaks something.
- if foo:
- do_bar()
- '''
- return baz
-
- def tricky_function():
- # Commented out because its breaks something.
- #if foo:
- #do_bar()
- return baz
-
-
- def tricky_function():
- # Commented out because its breaks something.
- # if foo:
- # do_bar()
- return baz
-
-**Good**
-
-.. code-block:: python
-
- def tricky_function():
- # Commented out because its breaks something.
- #if foo:
- # do_bar()
- return baz
-
-Note that comment text is properly written and separated from the hash by a
-space. Commented code is not separated from the hash by an additional space;
-this helps when uncommented the code.
-
-The Basics
-::::::::::
-
-
-Code Comments
--------------
-
-Information regarding code comments is taken from PEP 008 (http://www.python.org/dev/peps/pep-0008/).
-Block comment styling should be used when commenting out multiple lines of code.: ::
-
- Block comments generally apply to some (or all) code that follows them,
- and are indented to the same level as that code. Each line of a block
- comment starts with a # and a single space (unless it is indented text
- inside the comment).
- Paragraphs inside a block comment are separated by a line containing a
- single #.
-
-In-line comments are used for individual lines and should be used sparingly.: ::
-
- An inline comment is a comment on the same line as a statement. Inline
- comments should be separated by at least two spaces from the statement.
- They should start with a # and a single space.
- Inline comments are unnecessary and in fact distracting if they state
- the obvious. Don't do this:
- x = x + 1 # Increment x
- But sometimes, this is useful: ::
- x = x + 1 # Compensate for border
-
-Docstrings
------------
+.. _sphinx-ref:
-PEP 257 is the primary reference for docstrings. (http://www.python.org/dev/peps/pep-0257/)
+Sphinx
+~~~~~~
-There are two types of docstrings, one-line and multi-line. Their names
-should be fairly self explanatory.
-One-line docstrings: ::
+Sphinx_ is far and away the most popular python documentation
+tool. **Use it.** It converts :ref:`restructuredtext-ref` markup language
+into a range of output formats including HTML, LaTeX (for printable
+PDF versions), manual pages, and plain text.
- def kos_root():
- """Return the pathname of the KOS root directory."""
- global _kos_root
- if _kos_root: return _kos_root
- ...
+There is also **great**, **free** hosting for your Sphinx_ docs:
+`Read The Docs`_. Use it. You can configure it with commit hooks to
+your source repository so that rebuilding your documentation will
+happen automatically.
-Multi-line docstrings: ::
+.. note::
- def complex(real=0.0, imag=0.0):
- """Form a complex number.
+ Sphinx is famous for its API generation, but it also works well
+ for general project documentation. This Guide is built with
+ Sphinx_ and is hosted on `Read The Docs`_
- Keyword arguments:
- real -- the real part (default 0.0)
- imag -- the imaginary part (default 0.0)
+.. _Sphinx: http://sphinx.pocoo.org
+.. _Read The Docs: http://readthedocs.org
- """
- if imag == 0.0 and real == 0.0: return complex_zero
- ...
+.. _restructuredtext-ref:
+reStructuredText
+~~~~~~~~~~~~~~~~
-.. _sphinx-ref:
+Most Python documentation is written with reStructuredText_. It's like
+Markdown with all the optional extensions built in.
+The `reStructuredText Primer`_ and the `reStructuredText Quick
+Reference`_ should help you familiarize yourself with its syntax.
-Sphinx
-------
+.. _reStructuredText: http://docutils.sourceforge.net/rst.html
+.. _reStructuredText Primer: http://sphinx.pocoo.org/rest.html
+.. _reStructuredText Quick Reference: http://docutils.sourceforge.net/docs/user/rst/quickref.html
-Sphinx_ is a tool which converts documentation in the :ref:`restructuredtext-ref`
-markup language into a range of output formats including HTML, LaTeX (for
-printable PDF versions), manual pages and plain text.
-There is also a great free hosting for your Sphinx_ docs: `Read The Docs`_
+Code Documentation Advice
+-------------------------
-.. note:: This Guide is built with Sphinx_ and hosted on `Read The Docs`_
+Comments clarify code and begin with a hash (``#``).
-.. _Sphinx: http://sphinx.pocoo.org
-.. _Read The Docs: http://readthedocs.org
+.. _docstring-ref:
-.. _restructuredtext-ref:
+In Python, *docstrings* describe modules, classes, and functions: ::
+ def square_and_rooter(x):
+ """Returns the square root of self times self."""
+ ...
-reStructuredText
-----------------
+In general, follow the `comment section of PEP 0008`_ (the "Python Style Guide").
-Most Python documentation is written with reStructuredText_. The
-`reStructuredText Primer `_ and the
-`reStructuredText Quick Reference `_
-should help you familiarize yourself with its syntax.
+.. _comment section of PEP 0008: http://www.python.org/dev/peps/pep-0008/#comments
+
+Commenting Sections of Code
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+*Do not use triple-quote strings to comment code*. This is not a good
+practice, because line-oriented command-line tools such as grep will
+not be aware that the commented code is inactive. It is better to add
+hashes at the proper indentation level for every commented line. Your
+editor probably has the ability to do this easily, and it is worth
+learning the comment/uncomment toggle. (*e.g.* ctrl-v on Vim)
+
+Docstrings and Magic
+~~~~~~~~~~~~~~~~~~~~
+
+Some tools use docstrings to embed more-than-documentation behavior,
+such as unit test logic. Those can be nice, but you won't ever go
+wrong with vanilla "here's what this does."
+
+Docstrings versus Block comments
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+These aren't interchangeable. For a function or class, the leading
+comment block is a programmer's note. The docstring describes the
+operation of the function or class: ::
+
+ # This function slows down program execution for some reason.
+ def square_and_rooter(x):
+ """Returns the square root of self times self."""
+ ...
+
+.. seealso:: Further reading on docstrings: `PEP 0257`_
+
+.. _PEP 0257: http://www.python.org/dev/peps/pep-0257/
-.. _reStructuredText: http://docutils.sourceforge.net/rst.html
Other Tools
-:::::::::::
+-----------
+
+You might see these in the wild. Use :ref:`sphinx-ref`.
+
+Pycco_
+ Pycco is a "literate-programming-style documentation generator"
+ and is a port of the node.js Docco_. It makes code into a
+ side-by-side HTML code and documentation.
+.. _Pycco: http://fitzgen.github.com/pycco
+.. _Docco: http://jashkenas.github.com/docco
-Epydoc
-------
-`Epydoc `_ generates API documentation based on docstrings.
-Epydoc is able to parse docstrings marked up with :ref:`reStructuredText-ref`,
-`Javadoc `_,
-`epytext `_ or plaintext.
-It supports various output formats, most notable HTML, PDF or LaTeX documents.
+Ronn_
+ Ronn builds unix manuals. It converts human readable textfiles to roff for terminal display, and also to HTML for the web.
-The development of Epydoc is discontinued. You should use :ref:`sphinx-ref` instead.
+.. _Ronn: https://github.com/rtomayko/ronn
-pycco / docco / shocco
-----------------------
+Epydoc_
+ Epydoc is discontinued. Use :ref:`sphinx-ref` instead.
-Ronn
-----
+.. _Epydoc: http://epydoc.sourceforge.net
From b8a41ac61fcbda3e5b1a00d9066c4060a890f299 Mon Sep 17 00:00:00 2001
From: Clint Howarth
Date: Sat, 22 Sep 2012 23:51:59 -0400
Subject: [PATCH 0051/1232] build out header matter, clean up formatting
---
docs/writing/license.rst | 64 ++++++++++++++--------------------------
1 file changed, 22 insertions(+), 42 deletions(-)
diff --git a/docs/writing/license.rst b/docs/writing/license.rst
index 3b4f479d0..9e759baf6 100644
--- a/docs/writing/license.rst
+++ b/docs/writing/license.rst
@@ -1,16 +1,21 @@
Choosing a License
==================
-Open source.
+Your source publication *needs* a license. In the US, if no license is
+specified, users have no legal right to download, modify, or
+distribute. Furthermore, people can't contribute to your code unless
+you tell them what rules to play by. It's complicated, so here are
+some pointers:
-There are plenty of `open source licenses `_
-available to choose from.
+Open source. There are plenty of `open source licenses
+`_ available to choose
+from.
In general, these licenses tend to fall into one of two categories:
1. licenses that focus more on the user's freedom to do with the
software as they please (these are the more-permissive open
- source licenses such as the MIT, BSD, & Apache), and
+ source licenses such as the MIT, BSD, & Apache).
2. licenses that focus more on making sure that the code itself —
including any changes made to it and distributed along with it —
@@ -22,51 +27,26 @@ someone to add code to the software and distribute it without also
including the source code for their changes.
To help you choose one for your project, there's a `license chooser `_,
-use it.
+**use it**.
+**More-Permissive**
-More-Permissive
-:::::::::::::::
+- PSFL (Python Software Foundation License) -- for contributing to python itself
+- MIT / BSD / ISC
-PSFL
-----
+ + MIT (X11)
+ + New BSD
+ + ISC
+- Apache
-MIT / BSD / ISC
----------------
+**Less-Permissive:**
+- LGPL
+- GPL
-MIT (X11)
-`````````
+ + GPLv2
+ + GPLv3
-New BSD
-```````
-
-ISC
-```
-
-Apache
-------
-
-
-Less-Permissive
-:::::::::::::::
-
-
-LGPL
-----
-
-
-
-GPL
----
-
-
-GPLv2
-`````
-
-
-GPLv3
-`````
From e36fd9d8cb6faab39a7c6f70325cd76e491cb708 Mon Sep 17 00:00:00 2001
From: Clint Howarth
Date: Sat, 22 Sep 2012 23:58:28 -0400
Subject: [PATCH 0052/1232] add section on emacs
---
docs/dev/env.rst | 19 +++++++++++++++++--
1 file changed, 17 insertions(+), 2 deletions(-)
diff --git a/docs/dev/env.rst b/docs/dev/env.rst
index 88dd0d22f..7769e4cf4 100644
--- a/docs/dev/env.rst
+++ b/docs/dev/env.rst
@@ -64,7 +64,7 @@ Python-mode
^^^^^^^^^^^
Python-mode_ is complex solution in VIM for work with python code.
-It's have:
+It has:
- Async python code checking (pylint, pyflakes, pep8, mccabe) in any combination;
- Code refactoring and autocompletion with Rope;
@@ -90,6 +90,21 @@ And more stuff.
.. todo:: add supertab notes
+Emacs
+-----
+
+Emacs is a powerful text editor. It's fully programmable (lisp), but
+it can be some work to wire up correctly. A good start if you're
+already an Emacs user is `Python Programming in Emacs`_ at EmacsWiki.
+
+1. Emacs itself comes with a python mode.
+2. Python ships with an alternate version:
+ `python-mode.el `_
+3. Fabián Ezequiel Gallina's provides nice functionality and
+ behavior out of the box: `python.el `_
+
+.. _Python Programming in Emacs: http://emacswiki.org/emacs/PythonProgrammingInEmacs
+
TextMate
--------
@@ -202,7 +217,7 @@ environment, just remove the directory it was installed into. (In this
case, it would be ``rm -rf venv``).
Other Notes
-~~~~~~~~~~~
+^^^^^^^^^^^
Running ``virtualenv`` with the option ``--no-site-packages`` will not
include the packages that are installed globally. This can be useful
From e86d571a403d0a50415673b73672286ea139f9b3 Mon Sep 17 00:00:00 2001
From: Kwpolska
Date: Fri, 28 Sep 2012 20:02:05 +0200
Subject: [PATCH 0053/1232] html_title
Signed-off-by: Kwpolska
---
docs/conf.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/conf.py b/docs/conf.py
index ad90eb21f..b2bcce8da 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -103,7 +103,7 @@
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
-#html_title = None
+html_title = 'The Hitchhiker’s Guide to Python'
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
From ff1157d0383ee245941e50829af0eb6b2f0ac52a Mon Sep 17 00:00:00 2001
From: osscca
Date: Fri, 28 Sep 2012 21:08:42 +0200
Subject: [PATCH 0054/1232] Added NINJA-IDE to IDEs
---
docs/dev/env.rst | 15 +++++++++++++--
1 file changed, 13 insertions(+), 2 deletions(-)
diff --git a/docs/dev/env.rst b/docs/dev/env.rst
index 7769e4cf4..9641227d5 100644
--- a/docs/dev/env.rst
+++ b/docs/dev/env.rst
@@ -17,7 +17,7 @@ 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
the default settings for indentation and line-wrapping to values compliant with
`PEP 8 `_. In your home directory,
-open a file called `.vimrc` and add the following lines: ::
+open a file called `.vimrc` and add the following lines:::
set textwidth=79
set shiftwidth=4
@@ -142,7 +142,7 @@ The most popular Eclipse plugin for Python development is Aptana's
Komodo IDE
------------
+----------
`Komodo IDE `_ is developed by
ActiveState and is a commercial IDE for Windows, Mac
and Linux.
@@ -167,6 +167,17 @@ WingIDE
Windows, and Mac (as an X11 application, which frustrates some Mac users).
+NINJA-IDE
+---------
+
+`NINJA-IDE `_ (from the recursive acronym: "Ninja-IDE
+Is Not Just Another IDE", is a cross-platform IDE, specially designed to build
+Python applications, and runs on Linux/X11, Mac OS X and Windows desktop operating
+systems. Installers for these platforms can be downloaded from the website.
+
+NINJA-IDE is open-source software (GPLv3 licence) and is developed in Python and
+Qt. The source files can be downloaded from `GitHub `_.
+
Interpreter Tools
:::::::::::::::::
From 852edbee259010bf7285c84c7cd0d35107f20118 Mon Sep 17 00:00:00 2001
From: Johannes
Date: Sat, 6 Oct 2012 12:49:08 +0200
Subject: [PATCH 0055/1232] Fix typo
---
docs/writing/structure.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index 35dd43254..76d0b0847 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -39,7 +39,7 @@ include:
and if conversely the class Carpenter needs to import Table and Chair,
to answer the question carpenter.whatdo(), then you
have a circular dependency. In this case you will have to resort to
- fragile hacks such has using import statements inside
+ fragile hacks such as using import statements inside
methods or functions.
- Hidden coupling: each and every change in Table's implementation
From 0d4865ed66f8e98b8169760fe666ef7f9a4422b1 Mon Sep 17 00:00:00 2001
From: Harold Cooper
Date: Sun, 7 Oct 2012 12:41:50 -0700
Subject: [PATCH 0056/1232] use double-underscore for temporary variable, as
encouraged elsewhere in this file
---
docs/writing/style.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index 58ce01987..1f26605e6 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -321,7 +321,7 @@ Instead, use a list comprehension:
.. code-block:: python
- four_lists = [[] for _ in xrange(4)]
+ four_lists = [[] for __ in xrange(4)]
A common idiom for creating strings is to use `join `_ on an empty string.::
From b531d055d8cf5853175e6349ec66db5ce162332a Mon Sep 17 00:00:00 2001
From: Andrew Macgregor
Date: Sun, 14 Oct 2012 10:26:17 +0800
Subject: [PATCH 0057/1232] making html_tile a unicode string to prevent errors
in Sphinx
---
docs/conf.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/conf.py b/docs/conf.py
index b2bcce8da..936110574 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -103,7 +103,7 @@
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
-html_title = 'The Hitchhiker’s Guide to Python'
+html_title = u'The Hitchhiker’s Guide to Python'
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
From 6f444414188c0e0b0fffdc2a39be92d18677a4d8 Mon Sep 17 00:00:00 2001
From: Andrew Macgregor
Date: Sun, 14 Oct 2012 10:26:17 +0800
Subject: [PATCH 0058/1232] making html_title a unicode string to prevent
errors in Sphinx
---
docs/conf.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/conf.py b/docs/conf.py
index b2bcce8da..936110574 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -103,7 +103,7 @@
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
-html_title = 'The Hitchhiker’s Guide to Python'
+html_title = u'The Hitchhiker’s Guide to Python'
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
From 22b85c77c92d46178b094987cc8d071615277b48 Mon Sep 17 00:00:00 2001
From: Andrew Macgregor
Date: Mon, 15 Oct 2012 14:12:14 +0800
Subject: [PATCH 0059/1232] fixed community ref pointed to by intro/duction
---
docs/intro/community.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/intro/community.rst b/docs/intro/community.rst
index c9635c0a0..8ae20192d 100644
--- a/docs/intro/community.rst
+++ b/docs/intro/community.rst
@@ -1,4 +1,4 @@
-.. _the_community:
+.. _the-community:
The Community
=============
From 470b548a9a306c55519ca6f036ec7f3df6e2402f Mon Sep 17 00:00:00 2001
From: Andrew Macgregor
Date: Mon, 15 Oct 2012 14:42:57 +0800
Subject: [PATCH 0060/1232] adding a valid label for installation.rst to ref to
---
docs/starting/which-python.rst | 2 ++
1 file changed, 2 insertions(+)
diff --git a/docs/starting/which-python.rst b/docs/starting/which-python.rst
index af72adba7..240425280 100644
--- a/docs/starting/which-python.rst
+++ b/docs/starting/which-python.rst
@@ -1,6 +1,8 @@
Picking an Interpreter
======================
+.. _which-python:
+
Which Python to use?
From 773235508755e06fc9b4a0b186b169aeb24a484b Mon Sep 17 00:00:00 2001
From: Andrew Macgregor
Date: Tue, 16 Oct 2012 20:44:34 +0800
Subject: [PATCH 0061/1232] fix minor white space issue causing warning
---
docs/intro/learning.rst | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/docs/intro/learning.rst b/docs/intro/learning.rst
index 0f38d6eeb..5425d84f3 100644
--- a/docs/intro/learning.rst
+++ b/docs/intro/learning.rst
@@ -65,8 +65,8 @@ Python Koans
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
-teaching basic python concepts. By fixing assertion statements that fail in a
- test script, this provides sequential steps to learning python.
+teaching basic python concepts. By fixing assertion statements that fail in a
+test script, this provides sequential steps to learning python.
For those used to languages and figuring out puzzles on their own, this can be
a fun, attractive option. For those new to python and programming, having an
From f1651e1dc8e4af70ed67f3681987354cde5e9196 Mon Sep 17 00:00:00 2001
From: Andrew Macgregor
Date: Tue, 16 Oct 2012 22:04:15 +0800
Subject: [PATCH 0062/1232] looks like a typo, was perhaps meant to be link to
decorators but that is only a few lines later
---
docs/writing/structure.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index 76d0b0847..594517485 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -266,7 +266,7 @@ logic (called pure functions) allow the following benefits:
- Pure functions are easier to test with unit-tests: There is less
need for complex context setup and data cleaning afterwards.
-- Pure functions are easier to manipulate, decorate_, and pass-around.
+- Pure functions are easier to manipulate, decorate, and pass-around.
In summary, pure functions, without any context or side-effects, are more
efficient building blocks than classes and objects for some architectures.
From d8bc8758135fb59e1e8a46d2c4d48890963f377b Mon Sep 17 00:00:00 2001
From: Andrew Macgregor
Date: Tue, 16 Oct 2012 22:10:25 +0800
Subject: [PATCH 0063/1232] using anonymous hyperlinks to avoid duplicate
explicit name warnings see:
http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#anonymous-hyperlinks
---
docs/scenarios/db.rst | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/docs/scenarios/db.rst b/docs/scenarios/db.rst
index b17a15337..4f03058c2 100644
--- a/docs/scenarios/db.rst
+++ b/docs/scenarios/db.rst
@@ -10,8 +10,8 @@ Nearly all Python database modules such as `sqlite3`, `psycopg` and
`mysql-python` conform to this interface.
Tutorials that explain how to work with modules that conform to this interface can be found
-`here `_ and
-`here `_.
+`here `__ and
+`here `__.
SQLAlchemy
----------
From f0834bcfaf80849884b0bc1a3772b3b99128b78a Mon Sep 17 00:00:00 2001
From: Andrew Macgregor
Date: Tue, 16 Oct 2012 22:21:32 +0800
Subject: [PATCH 0064/1232] Conventions header was throwing inconsistent level
warning. Fixed this and later headings to match rest of page.
---
docs/writing/style.rst | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index 58ce01987..528eb2bda 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -416,12 +416,12 @@ Then run it on a file or series of files to get a report of any violations.
optparse.py:544:21: W601 .has_key() is deprecated, use 'in'
Conventions
-:::::::::::
+----------------
Here are some conventions you should follow to make your code easier to read.
Check if variable equals a constant
------------------------------------
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You don't need to explicitly compare a value to True, or None, or 0 - you can
just add it to the if statement. See `Truth Value Testing
@@ -455,7 +455,7 @@ list of what is considered false.
print 'attr is None!'
Access a Dictionary Element
----------------------------
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
Don't use the ``has_key`` function. Instead use ``x in d`` syntax, or pass
a default argument to ``get``.
@@ -484,7 +484,7 @@ a default argument to ``get``.
print d['hello']
Short Ways to Manipulate Lists
-------------------------------
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
`List comprehensions
`_
@@ -548,7 +548,7 @@ manually. Moreover,
it is better optimized for iterators.
Read From a File
-----------------
+~~~~~~~~~~~~~~~~
Use the ``with open`` syntax to read from files. This will automatically close
files for you.
@@ -574,7 +574,7 @@ The ``with`` statement is better because it will ensure you always close the
file, even if an exception is raised.
Returning Multiple Values from a Function
------------------------------------------
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Python supports returning multiple values from a function as a comma-separated
list, so you don't have to create an object or dictionary and pack multiple
From 655c1bdac9dee02bcf7f1a1a9948d2404cd2709c Mon Sep 17 00:00:00 2001
From: Andrew Macgregor
Date: Tue, 16 Oct 2012 23:19:54 +0800
Subject: [PATCH 0065/1232] provide valid link for YAGNI
---
docs/writing/style.rst | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index 528eb2bda..fbb41a8ee 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -114,10 +114,10 @@ Those two possibilities are better avoided without any strong reason to not
follow the syntax that is the closest to the function definition: ``send('Hello',
'World', cc='Cthulhu', bcc='God')``.
-As a side note, following YAGNI_ 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 new optional argument and its
-logic when needed.
+As a side note, following `YAGNI `_
+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
+new optional argument and its logic when needed.
The **arbitrary argument list** is the third way to pass arguments to a
function. If the function intention is better expressed by a signature with an
From d13792a3a2ac5b0cbc97ee66e88e5737f9b17689 Mon Sep 17 00:00:00 2001
From: Kenneth Reitz
Date: Wed, 17 Oct 2012 09:21:40 -0700
Subject: [PATCH 0066/1232] death to curly quotes!
---
docs/conf.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/conf.py b/docs/conf.py
index b2bcce8da..4dec12df5 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -103,7 +103,7 @@
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
-html_title = 'The Hitchhiker’s Guide to Python'
+html_title = 'The Hitchhiker\'s Guide to Python'
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
From 6da56aff38e07d228ccd9ae7301888f120122a8a Mon Sep 17 00:00:00 2001
From: Tasos Latsas
Date: Tue, 23 Oct 2012 20:34:30 +0300
Subject: [PATCH 0067/1232] Info about the Salt stack
---
docs/scenarios/admin.rst | 51 ++++++++++++++++++++++++++++++++++++++++
1 file changed, 51 insertions(+)
diff --git a/docs/scenarios/admin.rst b/docs/scenarios/admin.rst
index 425a4e3d4..a489d3a04 100644
--- a/docs/scenarios/admin.rst
+++ b/docs/scenarios/admin.rst
@@ -68,6 +68,57 @@ programs, and host grouping.
`Fabric Documentation `_
+Salt
+----
+
+`Salt `_ is an open source infrastructure management tool.
+It supports remote command execution from a central point (master host) to multiple
+hosts (minions). It also supports system states which can be used to configure
+multiple servers using simple template files.
+
+Salt supports python versions 2.6 and 2.7 and can be installed via pip:
+
+.. code-block:: bash
+
+ $ pip install salt
+
+After configuring a master server and any number of minion hosts, we can run arbitrary
+shell commands or use pre-built modules of complex commands on our minions.
+
+The following command lists all available minion hosts, using the ping module.
+
+.. code-block:: bash
+
+ $ salt '*' test.ping
+
+The host filtering is acomplished by matching the minion id, or using the grains system.
+The `grains `_ system
+uses static host information like the operating system version or the CPU architecture to
+provide a host taxonomy for the salt modules.
+
+The following command lists all available minions running CentOS using the grains system:
+
+.. code-block:: bash
+
+ $ salt -G 'os:CentOS' test.ping
+
+Salt also provides a state system. States can be used to configure the minion hosts.
+
+For example, when a minion host is ordered to read the following state file, will install
+and start the Apache server:
+
+.. code-block:: yaml
+
+ apache:
+ pkg:
+ - installed
+ service:
+ - running
+
+State files can be written using YAML, the Jinja2 template system or pure python.
+
+ `Salt Documentation `_
+
Chef
----
From ffdde4ac3eadf0bcfe2cb25f1e6cf5ce1701ebc7 Mon Sep 17 00:00:00 2001
From: Artie Gold
Date: Sun, 28 Oct 2012 15:53:36 -0500
Subject: [PATCH 0068/1232] Small text fix. It's "its" not "it's" here.
---
docs/writing/structure.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index 76d0b0847..b89944ae1 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -251,7 +251,7 @@ Another way to say the same thing is to suggest using functions and procedures
with as few implicit contexts and side-effects as possible. A function's
implicit context is made up of any of the global variables or items in the persistence layer
that are accessed from within the function. Side-effects are the changes that a function makes
-to it's implicit context. If a function saves or deletes data in a global variable or
+to its implicit context. If a function saves or deletes data in a global variable or
in the persistence layer, it is said to have a side-effect.
Carefully isolating functions with context and side-effects from functions with
From bbfa4792276ccb1e556ea15c2cbb32861e005093 Mon Sep 17 00:00:00 2001
From: Chris Warrick
Date: Sun, 11 Nov 2012 21:04:00 +0100
Subject: [PATCH 0069/1232] Fix a tiny typo
---
docs/writing/style.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index 58ce01987..706ee7a8b 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -107,7 +107,7 @@ passed another value.
Calling a function with keyword arguments can be done in multiple ways in Python,
for example it is possible to follow the order of arguments in the definition without
-explicitly naming the arguments, like in ``send('Hello', 'World', 'Cthulhu`, 'God')``,
+explicitly naming the arguments, like in ``send('Hello', 'World', 'Cthulhu', 'God')``,
sending a blank carbon copy to God. It would also be possible to name arguments in
another order, like in ``send('Hello again', 'World', bcc='God', cc='Cthulhu')``.
Those two possibilities are better avoided without any strong reason to not
From d7704e4808c985e3dde341c2bd86046496da63c3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Valentin-Costel=20H=C4=83loiu?=
Date: Mon, 12 Nov 2012 04:28:38 +0200
Subject: [PATCH 0070/1232] Update link to latest windows python version
---
docs/starting/install/win.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/starting/install/win.rst b/docs/starting/install/win.rst
index a04e71888..bcc9445e4 100644
--- a/docs/starting/install/win.rst
+++ b/docs/starting/install/win.rst
@@ -3,7 +3,7 @@
Installing Python on Windows
============================
-First, download the `latest version `_
+First, download the `latest version `_
of Python 2 from the official Website. If you want to be sure you are installing a fully
up-to-date version then use the "Windows Installer" link from the home page of the
`Python.org web site `_ .
From 8d904298130a31c11c8c0d97ca374cdfe587fa80 Mon Sep 17 00:00:00 2001
From: Pengkui Luo
Date: Wed, 14 Nov 2012 04:02:58 -0600
Subject: [PATCH 0071/1232] Update docs/starting/which-python.rst
---
docs/starting/which-python.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/starting/which-python.rst b/docs/starting/which-python.rst
index af72adba7..ed49f137c 100644
--- a/docs/starting/which-python.rst
+++ b/docs/starting/which-python.rst
@@ -50,7 +50,7 @@ level of compatibility with Python packages and C extension modules.
If you are writing open-source Python code and want to reach the widest possible
audience, targeting CPython is your best bet. If you need to use any packages
-that are rely on C extensions for their functionality (eg: numpy) then CPython
+that rely on C extensions for their functionality (eg: numpy) then CPython
is your only choice.
Being the reference implementation, all versions of the Python language are
From 64934821c462b1f13e2571f1a8b4252bcb9a0199 Mon Sep 17 00:00:00 2001
From: Pengkui Luo
Date: Wed, 14 Nov 2012 04:48:21 -0600
Subject: [PATCH 0072/1232] Update docs/dev/env.rst
.vimrc file: added 'autoindent'; added comments to illustrate.
---
docs/dev/env.rst | 13 +++++++------
1 file changed, 7 insertions(+), 6 deletions(-)
diff --git a/docs/dev/env.rst b/docs/dev/env.rst
index 9641227d5..3ccb15e6e 100644
--- a/docs/dev/env.rst
+++ b/docs/dev/env.rst
@@ -19,12 +19,13 @@ the default settings for indentation and line-wrapping to values compliant with
`PEP 8 `_. In your home directory,
open a file called `.vimrc` and add the following lines:::
- set textwidth=79
- set shiftwidth=4
- set tabstop=4
- set expandtab
- set softtabstop=4
- set shiftround
+ set textwidth=79 " lines longer than 79 columns will be broken
+ set shiftwidth=4 " operation >> indents 4 columns; << unindents 4 columns
+ set tabstop=4 " an hard TAB displays as 4 columns
+ set expandtab " insert spaces when hitting TABs
+ set softtabstop=4 " insert/delete 4 spaces when hitting a TAB/BACKSPACE
+ set shiftround " round indent to multiple of 'shiftwidth'
+ set autoindent " align the new line indent with the previous line
With these settings, newlines are inserted after 79 characters and indentation
is set to 4 spaces per tab. If you also use VIM for other languages, there is a
From fafc1055a235f28bc9b0bddc44226a03c6db2efe Mon Sep 17 00:00:00 2001
From: Glen
Date: Thu, 15 Nov 2012 16:55:16 -0800
Subject: [PATCH 0073/1232] Update Readme.rst
Corrected 'a almost' to 'an almost'
---
Readme.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Readme.rst b/Readme.rst
index def543b4c..48473dc00 100644
--- a/Readme.rst
+++ b/Readme.rst
@@ -23,6 +23,6 @@ Topics include:
- How to interface w/ hg from git easily
- what libraries to use for what
-If you are not fond of reading reStructuredText, there is a
+If you are not fond of reading reStructuredText, there is an
almost up-to-date `HTML version at docs.python-guide.org
`_.
From 19db184eb914bce20930ce6e0e2d9ebf8f8b4f9b Mon Sep 17 00:00:00 2001
From: Artie Gold
Date: Thu, 15 Nov 2012 23:13:58 -0600
Subject: [PATCH 0074/1232] Add notes that --no-site-packages is default
behavior for virtualenv from version 1.7 onward. Close #193.
---
docs/dev/env.rst | 2 ++
1 file changed, 2 insertions(+)
diff --git a/docs/dev/env.rst b/docs/dev/env.rst
index 9641227d5..9fc87ac93 100644
--- a/docs/dev/env.rst
+++ b/docs/dev/env.rst
@@ -233,6 +233,7 @@ Other Notes
Running ``virtualenv`` with the option ``--no-site-packages`` will not
include the packages that are installed globally. This can be useful
for keeping the package list clean in case it needs to be accessed later.
+[This is the default behavior for ``virtualenv`` 1.7 and later.]
In order to keep your environment consistent, it's a good idea to "freeze"
the current state of the environment packages. To do this, run
@@ -276,6 +277,7 @@ Put this into your `~/.bash_profile` (Linux/Mac) file:
This will prevent your virtualenvs from relying on your (global) site packages
directory, so that they are completely separate..
+[note: This is the default behavior for ``virtualenv`` 1.7 and later]
Other Tools
:::::::::::
From e66b3f1a388c165a1343eaf5cb66700b98940757 Mon Sep 17 00:00:00 2001
From: Alex Gaynor
Date: Tue, 20 Nov 2012 01:51:02 -0600
Subject: [PATCH 0075/1232] Remove a paragraph that wasn't adding value
In addition to be totally wrong about __init__, the description of generators was confusing (and more or less wrong).
---
docs/writing/style.rst | 4 ----
1 file changed, 4 deletions(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index d62b920fa..2d6316e5f 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -211,10 +211,6 @@ while privatising a public property might be a much harder operation.
Returning values
~~~~~~~~~~~~~~~~
-Python functions return a value, and you can control this return value with the
-return statement for all of them but the object constructor `__init__()` and the
-special case of generators.
-
When a function grows in complexity is not uncommon to use multiple return statements
inside the function's body. However, in order to keep a clear intent and a sustainable
readability level, it is preferable to avoid returning meaningful values from many
From e85c95b1f796bfb4881f30ecf47c24aeeaa1a6d9 Mon Sep 17 00:00:00 2001
From: suhail
Date: Fri, 23 Nov 2012 11:43:53 +0530
Subject: [PATCH 0076/1232] Update docs/_themes/kr/layout.html
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Line 27: var ga2 = document.createElement('script');ga.type = 'text/javascript';
i think it is wrongly typed ga.type, so i changed into ga2.type
change
======
ga2.type = 'text/javascript';
---
docs/_themes/kr/layout.html | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/_themes/kr/layout.html b/docs/_themes/kr/layout.html
index 890d48fe6..54f270d0b 100644
--- a/docs/_themes/kr/layout.html
+++ b/docs/_themes/kr/layout.html
@@ -24,7 +24,7 @@
_gaq2.push(['_trackPageview']);
(function() {
- var ga2 = document.createElement('script'); ga.type = 'text/javascript'; ga2.async = true;
+ var ga2 = document.createElement('script'); ga2.type = 'text/javascript'; ga2.async = true;
ga2.src = ('https:' == document.location.protocol ? 'https://ssl/' : 'http://www/') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga2, s);
})();
From 872bd300fcefeb58da78bf3ebbe597d864881b50 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Thomas=20Wei=C3=9Fschuh?=
Date: Fri, 23 Nov 2012 18:45:56 +0000
Subject: [PATCH 0077/1232] fix typos in web.rst
---
docs/scenarios/web.rst | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/docs/scenarios/web.rst b/docs/scenarios/web.rst
index 4dbcc4fd6..20fc710c3 100644
--- a/docs/scenarios/web.rst
+++ b/docs/scenarios/web.rst
@@ -164,7 +164,7 @@ support for Python 2.7 applications.
Heroku allows you to run as many Python web applications as you like, 24/7 and
free of charge. Heroku is best described as a horizontal scaling platform. They
start to charge you once you "scale" you application to run on more than one
-Dyno (abstacted servers) at a time.
+Dyno (abstracted servers) at a time.
Heroku publishes `step-by-step instructions
`_ on how to set up your first
@@ -212,7 +212,7 @@ Templating
Most WSGI applications are responding to HTTP requests to serve
content in HTML or other markup languages. Instead of generating directly
textual content from Python, the concept of separation of concerns
-advise us to use templates. A template engine manage a suite of
+advises us to use templates. A template engine manage a suite of
template files, with a system of hierarchy and inclusion to
avoid unnecessary repetition, and is in charge of rendering
(generating) the actual content, filling the static content
@@ -220,10 +220,10 @@ of the templates with the dynamic content generated by the
application.
As template files are
-sometime written by designers or front-end developpers,
+sometimes written by designers or front-end developers,
it can be difficult to handle increasing complexity.
-Some general good pratices apply to the part of the
+Some general good practices apply to the part of the
application passing dynamic content to the template engine,
and to the templates themselves.
@@ -233,7 +233,7 @@ and to the templates themselves.
it is easier to add some missing variable when needed than to remove
a likely unused variable later.
-- Many template engine allow for complex statements
+- Many template engines allow for complex statements
or assignments in the template itself, and many
allow some Python code to be evaluated in the
templates. This convenience can lead to uncontrolled
From 2210172c507fa025827de825a5f7bca79449ec2f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Thomas=20Wei=C3=9Fschuh?=
Date: Sat, 24 Nov 2012 12:41:44 +0000
Subject: [PATCH 0078/1232] fix typo in env.rst
---
docs/dev/env.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/dev/env.rst b/docs/dev/env.rst
index 3ccb15e6e..e91a9c5ba 100644
--- a/docs/dev/env.rst
+++ b/docs/dev/env.rst
@@ -74,7 +74,7 @@ It has:
- Virtual env support;
- Search by python documentation and run python code;
- More other things like auto pep8 error fixes;
-- Very customizable an documented as well;
+- Very customizable and documented as well;
- Have all required libraries in self;
And more stuff.
From d9d7283106b6e21000a44e98842f0fdecccf3af1 Mon Sep 17 00:00:00 2001
From: Sateesh
Date: Mon, 26 Nov 2012 23:41:05 +0530
Subject: [PATCH 0079/1232] Update docs/scenarios/scientific.rst
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
A free version of "Enthought Python Distribution" is available.
Modified to indicate the same and remove the statement that
'Enthought is not free'
---
docs/scenarios/scientific.rst | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/docs/scenarios/scientific.rst b/docs/scenarios/scientific.rst
index 0b2c16510..758f0a1d7 100644
--- a/docs/scenarios/scientific.rst
+++ b/docs/scenarios/scientific.rst
@@ -45,7 +45,10 @@ Enthought
Installing NumPy and SciPy can be a daunting task. Which is why the
`Enthought Python distribution `_ was created. With
Enthought, scientific python has never been easier (one click to install about
-100 scientific python packages). User beware: Enthought is not free.
+100 scientific python packages). The Enthought Python Distribution comes in two
+variants: a free version `EPD Free `_
+and a paid version with various `pricing options.
+`_
Matplotlib
----------
From 0ea7091a30f8b3e99320696253772645b0271796 Mon Sep 17 00:00:00 2001
From: Julian Berman
Date: Mon, 3 Dec 2012 21:56:22 -0500
Subject: [PATCH 0080/1232] Removed tuple example from style guide.
---
docs/writing/style.rst | 27 ---------------------------
1 file changed, 27 deletions(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index 2d6316e5f..55e16aa06 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -569,33 +569,6 @@ files for you.
The ``with`` statement is better because it will ensure you always close the
file, even if an exception is raised.
-Returning Multiple Values from a Function
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Python supports returning multiple values from a function as a comma-separated
-list, so you don't have to create an object or dictionary and pack multiple
-values in before you return
-
-**Bad**:
-
-.. code-block:: python
-
- def math_func(a):
- return {'square': a ** 2, 'cube': a ** 3}
-
- d = math_func(3)
- s = d['square']
- c = d['cube']
-
-**Good**:
-
-.. code-block:: python
-
- def math_func(a):
- return a ** 2, a ** 3
-
- square, cube = math_func(3)
-
Line Continuations
~~~~~~~~~~~~~~~~~~
From fd9f0db1cefcecee9579ab9b38d04d38ddecce28 Mon Sep 17 00:00:00 2001
From: Julian Berman
Date: Mon, 3 Dec 2012 22:26:40 -0500
Subject: [PATCH 0081/1232] First gotcha.
---
docs/contents.rst.inc | 1 +
docs/writing/gotchas.rst | 61 ++++++++++++++++++++++++++++++++++++++++
2 files changed, 62 insertions(+)
create mode 100644 docs/writing/gotchas.rst
diff --git a/docs/contents.rst.inc b/docs/contents.rst.inc
index ca3698329..31151a010 100644
--- a/docs/contents.rst.inc
+++ b/docs/contents.rst.inc
@@ -31,6 +31,7 @@ This part of the guide focuses on best practices for writing Python code.
writing/style
writing/documentation
writing/tests
+ writing/gotchas
writing/license
diff --git a/docs/writing/gotchas.rst b/docs/writing/gotchas.rst
new file mode 100644
index 000000000..e5e2d9b17
--- /dev/null
+++ b/docs/writing/gotchas.rst
@@ -0,0 +1,61 @@
+Common Gotchas
+==============
+
+For the most part, Python aims to be a clean and consistent language that
+avoid surprises, but there are a few cases where newcomers to the language
+often get tripped up.
+
+Some of these are intentional but surprising. Some could arguably be considered
+language warts. In general though, what follows is a collection of potentially
+tricky behavior that might seem strange at first glance, but is generally
+sensible despite surprise after learning of its existence.
+
+
+Mutable Default Arguments
+-------------------------
+
+Seemingly the *most* common surprise new Python programmers encounter is
+Python's treatment of mutable default arguments in function definitions.
+
+**What You Wrote**
+
+.. code-block:: python
+
+ def append_to(element, to=[]):
+ to.append(element)
+ return to
+
+**What You Might Have Expected to Happen**
+
+A new list is created each time the function is called if a second argument
+isn't provided.
+
+**What Does Happen**
+
+A new list is created *once* when the function is defined, and the same list is
+used in each successive call.
+
+Python's default arguments are evaluated *once* when the function is defined,
+not each time the function is called (like it is in say, Ruby). This means that
+if you use a mutable default argument and mutate it, you *will* and have
+mutated that object for all future calls to the function as well.
+
+**What You Should Do Instead**
+
+Create a new object each time the function is called, by using a default arg to
+signal that no argument was provided (``None`` is often a good choice).
+
+.. code-block:: python
+
+ def append_to(element, to=None):
+ if to is None:
+ to = []
+ to.append(element)
+ return to
+
+
+**When the Gotcha Isn't a Gotcha**
+
+Sometimes you specifically can "exploit" (read: use as intended) this behavior
+to maintain state between calls of a function. This is often done when writing
+a caching function.
From 4675c91fc598cdded4b2e7a235e947eda3d7db24 Mon Sep 17 00:00:00 2001
From: Julian Berman
Date: Tue, 4 Dec 2012 00:39:23 -0500
Subject: [PATCH 0082/1232] Late binding closures
---
docs/writing/gotchas.rst | 71 +++++++++++++++++++++++++++++++++++++---
1 file changed, 67 insertions(+), 4 deletions(-)
diff --git a/docs/writing/gotchas.rst b/docs/writing/gotchas.rst
index e5e2d9b17..15e900404 100644
--- a/docs/writing/gotchas.rst
+++ b/docs/writing/gotchas.rst
@@ -5,12 +5,14 @@ For the most part, Python aims to be a clean and consistent language that
avoid surprises, but there are a few cases where newcomers to the language
often get tripped up.
-Some of these are intentional but surprising. Some could arguably be considered
-language warts. In general though, what follows is a collection of potentially
-tricky behavior that might seem strange at first glance, but is generally
-sensible despite surprise after learning of its existence.
+Some of these are intentional but potentially surprising. Some could arguably
+be considered language warts. In general though, what follows is a collection
+of potentially tricky behavior that might seem strange at first glance, but is
+generally sensible once you're aware of the underlying cause for the surprise.
+.. _default_args:
+
Mutable Default Arguments
-------------------------
@@ -59,3 +61,64 @@ signal that no argument was provided (``None`` is often a good choice).
Sometimes you specifically can "exploit" (read: use as intended) this behavior
to maintain state between calls of a function. This is often done when writing
a caching function.
+
+
+Late Binding Closures
+---------------------
+
+Another common source of confusion is the way Python binds its variables in
+closures (or in the surrounding global scope).
+
+**What You Wrote**
+
+.. code-block:: python
+
+ def create_adders():
+ return [lambda x : i * x for i in range(5)]
+
+**What You Might Have Expected to Happen**
+
+A list containing five functions that each have their own closed-over ``i``
+variable that multiplies their argument.
+
+**What Does Happen**
+
+Five functions are created, but all of them just multiply ``x`` by 4.
+
+Python's closures are *late binding*. This means that names within closures are
+looked up at the time the inner function is *called*.
+
+Here, whenever *any* of the returned functions are called, the value of ``i``
+is looked up in the surrounding scope at call time, when by then the loop has
+completed and ``i`` is left with its final value of 4.
+
+What's particularly nasty about this gotcha is the seemingly prevalent
+misinformation that this has something to do with ``lambda``\s in Python.
+Functions created with a ``lambda`` expression are in no way special, and in
+fact the same exact behavior is exhibited by just using an ordinary ``def``:
+
+.. code-block:: python
+
+ def create_adders():
+ for i in range(5):
+ def adder(x):
+ return i * x
+ yield adder
+
+**What You Should Do Instead**
+
+Well. Here the general solution is arguably a bit of a hack. Due to Python's
+afformentioned behavior concerning evaluating default arguments to functions
+(see :ref:`default_args`), you can create a closure that binds immediately to
+its arguments by using a default arg like so:
+
+.. code-block:: python
+
+ def create_adders():
+ return [lambda x, i=i : i * x for i in range(5)]
+
+**When the Gotcha Isn't a Gotcha**
+
+When you want your closures to behave this way. Late binding is good in lots of
+situations. Looping to create unique functions is unfortunately a case where
+they can cause hiccups.
From be9a2563678898f189780d6c2e6c853fa4ae2d31 Mon Sep 17 00:00:00 2001
From: Mark Veronda
Date: Fri, 7 Dec 2012 16:55:03 -0500
Subject: [PATCH 0083/1232] Fixed some type-os
---
docs/contents.rst.inc | 2 +-
docs/scenarios/admin.rst | 2 +-
docs/scenarios/gui.rst | 2 +-
docs/scenarios/speed.rst | 4 ++--
docs/writing/style.rst | 2 +-
docs/writing/tests.rst | 2 +-
6 files changed, 7 insertions(+), 7 deletions(-)
diff --git a/docs/contents.rst.inc b/docs/contents.rst.inc
index ca3698329..4154d08f1 100644
--- a/docs/contents.rst.inc
+++ b/docs/contents.rst.inc
@@ -101,7 +101,7 @@ background information about Python, then focuses on next steps.
--------------------------------------
-Contibution notes and legal information are here (for those interested).
+Contribution notes and legal information are here (for those interested).
.. toctree::
:maxdepth: 2
diff --git a/docs/scenarios/admin.rst b/docs/scenarios/admin.rst
index a489d3a04..042f703ae 100644
--- a/docs/scenarios/admin.rst
+++ b/docs/scenarios/admin.rst
@@ -91,7 +91,7 @@ The following command lists all available minion hosts, using the ping module.
$ salt '*' test.ping
-The host filtering is acomplished by matching the minion id, or using the grains system.
+The host filtering is accomplished by matching the minion id, or using the grains system.
The `grains `_ system
uses static host information like the operating system version or the CPU architecture to
provide a host taxonomy for the salt modules.
diff --git a/docs/scenarios/gui.rst b/docs/scenarios/gui.rst
index a5c7d1afb..d40ac7e7f 100644
--- a/docs/scenarios/gui.rst
+++ b/docs/scenarios/gui.rst
@@ -40,7 +40,7 @@ Gtk
---
PyGTK provides Python bindings for the GTK+ toolkit. Like the GTK+ library
itself, it is currently licensed under the GNU LGPL. It is worth noting that
-PyGTK only currenty supports the Gtk-2.X API (NOT Gtk-3.0). It is currently
+PyGTK only currently supports the Gtk-2.X API (NOT Gtk-3.0). It is currently
recommended that PyGTK is not used for new projects and existing applications
be ported from PyGTK to PyGObject.
diff --git a/docs/scenarios/speed.rst b/docs/scenarios/speed.rst
index f0d6c7877..e20c563ba 100644
--- a/docs/scenarios/speed.rst
+++ b/docs/scenarios/speed.rst
@@ -42,7 +42,7 @@ The GIL
`The GIL`_ (Global Interpreter Lock) is how Python allows multiple threads to
operate at the same time. Python's memory management isn't entirely thread-safe,
-so the GIL is requried to prevents multiple threads from running the same
+so the GIL is required to prevents multiple threads from running the same
Python code at once.
David Beazley has a great `guide`_ on how the GIL operates. He also covers the
@@ -51,7 +51,7 @@ Python application requires a strong understanding of the GIL, how it affects
your specific application, how many cores you have, and where your application
bottlenecks are.
-C Extentions
+C Extensions
------------
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index 2d6316e5f..dee507bd7 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -151,7 +151,7 @@ clearer construct is sufficient to express the function's intention.
It is up to the programmer writing the function to determine which arguments
are positional arguments and which are optional keyword arguments, and to
decide whether to use the advanced techniques of arbitrary argument passing. If
-the advices above are followed wisely, it is possible and enjoyable to write
+the advice above is followed wisely, it is possible and enjoyable to write
Python functions that are:
* easy to read (the name and arguments need no explanations)
diff --git a/docs/writing/tests.rst b/docs/writing/tests.rst
index 975adf67b..d70d613d9 100644
--- a/docs/writing/tests.rst
+++ b/docs/writing/tests.rst
@@ -290,7 +290,7 @@ always returns the same result (but only for the duration of the test).
# get_search_results runs a search and iterates over the result
self.assertEqual(len(myapp.get_search_results(q="fish")), 3)
-Mock has many other ways you can configure it and control its behaviour.
+Mock has many other ways you can configure it and control its behavior.
`mock `_
From 2c22066f14adcb3973e1db2d646b9307ecdd8888 Mon Sep 17 00:00:00 2001
From: Baze Petrushev
Date: Mon, 10 Dec 2012 16:27:49 +0100
Subject: [PATCH 0084/1232] Added werkzeug entry under web frameworks section
---
docs/scenarios/web.rst | 12 ++++++++++++
1 file changed, 12 insertions(+)
diff --git a/docs/scenarios/web.rst b/docs/scenarios/web.rst
index 20fc710c3..7bdd1dd10 100644
--- a/docs/scenarios/web.rst
+++ b/docs/scenarios/web.rst
@@ -78,6 +78,18 @@ already exist to suit your needs.
email to flask@librelist.com and reply to the confirmation email.
+Werkzeug
+--------
+
+`Werkzeug `_ is not actually a real framework, but
+rather a very powerful set of tools for building web applications. It provides
+URL routing utilities, request and response objects and a basic development
+server. It is mostly used where users need bigger flexibility for their
+application that is not commonly found in other web frameworks.
+
+Support can be found on its `mailing list `_.
+
+
.. todo:: Explain Pyramid
From ca5321f0c9e1723284b6de6a4b420ff40381c486 Mon Sep 17 00:00:00 2001
From: Baze Petrushev
Date: Tue, 11 Dec 2012 12:47:53 +0100
Subject: [PATCH 0085/1232] Added networking section to scenarios.
Section includes:
- twisted
- pyzmq (for zeromq)
- gevent (a mention)
---
docs/contents.rst.inc | 1 +
docs/scenarios/network.rst | 32 ++++++++++++++++++++++++++++++++
2 files changed, 33 insertions(+)
create mode 100644 docs/scenarios/network.rst
diff --git a/docs/contents.rst.inc b/docs/contents.rst.inc
index 4154d08f1..175cfced5 100644
--- a/docs/contents.rst.inc
+++ b/docs/contents.rst.inc
@@ -49,6 +49,7 @@ different scenarios.
scenarios/cli
scenarios/gui
scenarios/db
+ scenarios/network
scenarios/admin
scenarios/ci
scenarios/speed
diff --git a/docs/scenarios/network.rst b/docs/scenarios/network.rst
new file mode 100644
index 000000000..0521089ed
--- /dev/null
+++ b/docs/scenarios/network.rst
@@ -0,0 +1,32 @@
+Networking
+==========
+
+Twisted
+-------
+
+`Twisted `_ is an event-driven networking engine. It can be
+used to build applications around many different networking protocols, including http servers
+and clients, applications using SMTP, POP3, IMAP or SSH protocols, instant messaging and
+`many more `_.
+
+PyZMQ
+-----
+
+`PyZMQ `_ is the Python binding for `ZeroMQ `_,
+which is a high-performance asynchronous messaging library. One great advantage is that ZeroMQ
+can be used for message queuing without message broker. The basic patterns for this are:
+
+- request-reply: connects a set of clients to a set of services. This is a remote procedure call
+ and task distribution pattern.
+- publish-subscribe: connects a set of publishers to a set of subscribers. This is a data
+ distribution pattern.
+- push-pull (or pipeline): connects nodes in a fan-out / fan-in pattern that can have multiple
+ steps, and loops. This is a parallel task distribution and collection pattern.
+
+For a quick start, read the `ZeroMQ guide `_.
+
+gevent
+------
+`gevent `_ is a coroutine-based Python networking library
+that uses greenlets and libevent event loop.
+
From 49371fe79742a96b13a3815485d97f8cd697ad6f Mon Sep 17 00:00:00 2001
From: Gergely Imreh
Date: Sun, 16 Dec 2012 14:37:07 +0800
Subject: [PATCH 0086/1232] Image Manipulation: add PIL install instructions
for Linux
Arch Linux and latest Ubuntu included.
---
docs/scenarios/imaging.rst | 19 ++++++++++++++++---
1 file changed, 16 insertions(+), 3 deletions(-)
diff --git a/docs/scenarios/imaging.rst b/docs/scenarios/imaging.rst
index 6a5c01780..8a1597221 100644
--- a/docs/scenarios/imaging.rst
+++ b/docs/scenarios/imaging.rst
@@ -26,11 +26,24 @@ to install. It has good setup instructions for all platforms.
Installing on Linux
~~~~~~~~~~~~~~~~~~~
-Ubuntu 11.04
+Arch Linux
+``````````
+
+PIL is maintained in the official community repository, and installed with the system installer as:
+
+.. code-block:: bash
+
+ $ sudo pacman -S python2-imaging
+
+Ubuntu 12.10
````````````
-.. todo::
- Notes on installing on Ubuntu 11.04
+Can be installed on the command line as:
+
+.. code-block:: bash
+
+ $ sudo apt-get install python-imaging
+
Installing on Mac OS X
~~~~~~~~~~~~~~~~~~~~~~
From 8c80931444ec7fb273d4110e2d5f9801c874051a Mon Sep 17 00:00:00 2001
From: Julian Berman
Date: Sun, 23 Dec 2012 17:26:36 -0500
Subject: [PATCH 0087/1232] Add doctest ext
---
docs/conf.py | 7 ++++++-
1 file changed, 6 insertions(+), 1 deletion(-)
diff --git a/docs/conf.py b/docs/conf.py
index 4dec12df5..9616262c2 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -25,7 +25,12 @@
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions = ['sphinx.ext.ifconfig', 'sphinx.ext.todo', 'sphinx.ext.intersphinx']
+extensions = [
+ 'sphinx.ext.ifconfig',
+ 'sphinx.ext.todo',
+ 'sphinx.ext.intersphinx',
+ 'sphinx.ext.doctest',
+]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
From 90f50c406ef1d58a285e499abd01f6e82c9cf768 Mon Sep 17 00:00:00 2001
From: Julian Berman
Date: Sun, 23 Dec 2012 17:30:00 -0500
Subject: [PATCH 0088/1232] Travis CI
---
.travis.yml | 6 ++++++
1 file changed, 6 insertions(+)
create mode 100644 .travis.yml
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 000000000..bce400b9a
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,6 @@
+language: python
+install: pip install sphinx
+script:
+ - make doctest
+ - make html
+
From ad4819476f01ee51c4a5f91c46672dfa305f1af5 Mon Sep 17 00:00:00 2001
From: Julian Berman
Date: Sun, 23 Dec 2012 17:56:52 -0500
Subject: [PATCH 0089/1232] Add doctests and switch to using headings.
---
docs/writing/gotchas.rst | 75 ++++++++++++++++++++++++++++++++--------
1 file changed, 60 insertions(+), 15 deletions(-)
diff --git a/docs/writing/gotchas.rst b/docs/writing/gotchas.rst
index 15e900404..51b810565 100644
--- a/docs/writing/gotchas.rst
+++ b/docs/writing/gotchas.rst
@@ -19,20 +19,39 @@ Mutable Default Arguments
Seemingly the *most* common surprise new Python programmers encounter is
Python's treatment of mutable default arguments in function definitions.
-**What You Wrote**
+What You Wrote
+~~~~~~~~~~~~~~
-.. code-block:: python
+.. testcode::
def append_to(element, to=[]):
to.append(element)
return to
-**What You Might Have Expected to Happen**
+What You Might Have Expected to Happen
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. testcode::
+
+ my_list = append_to(12)
+ print my_list
+
+ my_other_list = append_to(42)
+ print my_other_list
A new list is created each time the function is called if a second argument
-isn't provided.
+isn't provided, so that the output is::
+
+ [12]
+ [42]
+
+What Does Happen
+~~~~~~~~~~~~~~~~
+
+.. testoutput::
-**What Does Happen**
+ [12]
+ [12, 42]
A new list is created *once* when the function is defined, and the same list is
used in each successive call.
@@ -42,7 +61,8 @@ not each time the function is called (like it is in say, Ruby). This means that
if you use a mutable default argument and mutate it, you *will* and have
mutated that object for all future calls to the function as well.
-**What You Should Do Instead**
+What You Should Do Instead
+~~~~~~~~~~~~~~~~~~~~~~~~~~
Create a new object each time the function is called, by using a default arg to
signal that no argument was provided (``None`` is often a good choice).
@@ -56,7 +76,8 @@ signal that no argument was provided (``None`` is often a good choice).
return to
-**When the Gotcha Isn't a Gotcha**
+When the Gotcha Isn't a Gotcha
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sometimes you specifically can "exploit" (read: use as intended) this behavior
to maintain state between calls of a function. This is often done when writing
@@ -69,19 +90,41 @@ Late Binding Closures
Another common source of confusion is the way Python binds its variables in
closures (or in the surrounding global scope).
-**What You Wrote**
+What You Wrote
+~~~~~~~~~~~~~~
-.. code-block:: python
+.. testcode::
- def create_adders():
+ def create_multipliers():
return [lambda x : i * x for i in range(5)]
-**What You Might Have Expected to Happen**
+What You Might Have Expected to Happen
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. testcode::
+
+ for multiplier in create_multipliers():
+ print multiplier(2)
A list containing five functions that each have their own closed-over ``i``
-variable that multiplies their argument.
+variable that multiplies their argument, producing::
+
+ 0
+ 2
+ 4
+ 6
+ 8
+
+What Does Happen
+~~~~~~~~~~~~~~~~
+
+.. testoutput::
-**What Does Happen**
+ 8
+ 8
+ 8
+ 8
+ 8
Five functions are created, but all of them just multiply ``x`` by 4.
@@ -105,7 +148,8 @@ fact the same exact behavior is exhibited by just using an ordinary ``def``:
return i * x
yield adder
-**What You Should Do Instead**
+What You Should Do Instead
+~~~~~~~~~~~~~~~~~~~~~~~~~~
Well. Here the general solution is arguably a bit of a hack. Due to Python's
afformentioned behavior concerning evaluating default arguments to functions
@@ -117,7 +161,8 @@ its arguments by using a default arg like so:
def create_adders():
return [lambda x, i=i : i * x for i in range(5)]
-**When the Gotcha Isn't a Gotcha**
+When the Gotcha Isn't a Gotcha
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When you want your closures to behave this way. Late binding is good in lots of
situations. Looping to create unique functions is unfortunately a case where
From d0c4e0fa36ef96b4a1d5706ef78c8910b9b2f476 Mon Sep 17 00:00:00 2001
From: Matt Stiles
Date: Thu, 27 Dec 2012 14:07:53 -0500
Subject: [PATCH 0090/1232] Update docs/starting/install/osx.rst
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Fixed broken installation command.
---
docs/starting/install/osx.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/starting/install/osx.rst b/docs/starting/install/osx.rst
index 3da84a76b..883cac0f7 100644
--- a/docs/starting/install/osx.rst
+++ b/docs/starting/install/osx.rst
@@ -33,7 +33,7 @@ simply run
.. code-block:: console
- $ /usr/bin/ruby -e "$(/usr/bin/curl -fsSL https://raw.github.com/mxcl/homebrew/master/Library/Contributions/install_homebrew.rb)"
+ $ ruby -e "$(curl -fsSkL raw.github.com/mxcl/homebrew/go)"
Then, insert the Homebrew directory at the top of your ``PATH`` environment
variable. You can do this by adding the following line at the bottom of your
From faae04c3a3c89e8033e8e79181008aca4b81ae4f Mon Sep 17 00:00:00 2001
From: sirMackk
Date: Mon, 31 Dec 2012 10:22:38 -0500
Subject: [PATCH 0091/1232] Added scenario about web scraping using lxml
---
docs/scenarios/scrape.rst | 82 +++++++++++++++++++++++++++++++++++++++
1 file changed, 82 insertions(+)
create mode 100644 docs/scenarios/scrape.rst
diff --git a/docs/scenarios/scrape.rst b/docs/scenarios/scrape.rst
new file mode 100644
index 000000000..35379387d
--- /dev/null
+++ b/docs/scenarios/scrape.rst
@@ -0,0 +1,82 @@
+HTML Scraping
+=============
+
+Web Scraping
+------------
+
+Web sites are written using HTML, which means that each web page is a
+ structured document. Sometimes it would be great to obtain some data from
+them and preserve the structure while we're at it, but this isn't always easy
+ - it's not often that web sites provide their data in comfortable formats
+ such as `.csv`.
+
+This is where web scraping comes in. Web scraping is the practice of using
+computer program to sift through a web page and gather the data that you need
+in a format most useful to you.
+
+lxml
+----
+
+`lxml `_ is a pretty extensive library written for parsing
+XML and HTML documents, which you can easily install using `pip`. We will
+be using its `html` module to get data from this web page: `econpy '_ .
+
+First we shall import the required modules:
+
+.. code-block:: python
+
+ from lxml import html
+ from urllib2 import urlopen
+
+We will use `urllib2.urlopen` to retrieve the web page with our data and
+parse it using the `html` module:
+
+.. code-block:: python
+
+ page = urlopen('http://econpy.pythonanywhere.com/ex/001.html')
+ tree = html.fromstring(page.read())
+
+`tree` now contains the whole HTML file in a nice tree structure which
+we can go over in many different ways, one of which is using XPath. XPath
+is a way of locating information in structured documents such as HTML or XML
+pages. A good introduction to XPath is 'here '_ .
+One can also use various tools for obtaining the XPath of elements such as
+FireBug for Firefox or in Chrome you can right click an element, choose
+'Inspect element', highlight the code and the right click again and choose
+'Copy XPath'.
+
+After a quick analysis, we see that in our page the data is contained in
+two elements - one is a div with title 'buyer-name' and the other is a
+span with class 'item-price'. Knowing this we can create the correct XPath
+query and use the lxml `xpath` function like this:
+
+.. code-block:: python
+
+ #This will create a list of buyers:
+ buyers = tree.xpath('//div[@title="buyer-name"]/text()')
+ #This will create a list of prices
+ prices = tree.xpath('//span[@class="item-price"]/text()')
+
+Lets see what we got exactly:
+
+.. code-block:: python
+
+ print 'Buyers: ', buyers
+ print 'Prices: ', prices
+
+::
+ Buyers: ['Carson Busses', 'Earl E. Byrd', 'Patty Cakes',
+ 'Derri Anne Connecticut', 'Moe Dess', 'Leda Doggslife', 'Dan Druff',
+ 'Al Fresco', 'Ido Hoe', 'Howie Kisses', 'Len Lease', 'Phil Meup',
+ 'Ira Pent', 'Ben D. Rules', 'Ave Sectomy', 'Gary Shattire',
+ 'Bobbi Soks', 'Sheila Takya', 'Rose Tattoo', 'Moe Tell']
+
+ Prices: ['$29.95', '$8.37', '$15.26', '$19.25', '$19.25',
+ '$13.99', '$31.57', '$8.49', '$14.47', '$15.86', '$11.11',
+ '$15.98', '$16.27', '$7.50', '$50.85', '$14.26', '$5.68',
+ '$15.00', '$114.07', '$10.09']
+
+Congratulations! We have successfully scraped all the data we wanted from
+a web page using lxml and we have it stored in memory as two lists. Now we
+can either continue our work on it, analyzing it using python or we can
+export it to a file and share it with friends.
From 3aef3bd8ef0c9fa2c008e1fc31795af86cde34ce Mon Sep 17 00:00:00 2001
From: sirMackk
Date: Mon, 31 Dec 2012 10:27:29 -0500
Subject: [PATCH 0092/1232] 2nd draft of web scraping scenario
Fixed some markup.
---
docs/scenarios/scrape.rst | 19 ++++++++++---------
1 file changed, 10 insertions(+), 9 deletions(-)
diff --git a/docs/scenarios/scrape.rst b/docs/scenarios/scrape.rst
index 35379387d..b2bd0706f 100644
--- a/docs/scenarios/scrape.rst
+++ b/docs/scenarios/scrape.rst
@@ -5,10 +5,10 @@ Web Scraping
------------
Web sites are written using HTML, which means that each web page is a
- structured document. Sometimes it would be great to obtain some data from
-them and preserve the structure while we're at it, but this isn't always easy
- - it's not often that web sites provide their data in comfortable formats
- such as `.csv`.
+structured document. Sometimes it would be great to obtain some data from
+them and preserve the structure while we're at it, but this isn't always easy.
+It's not often that web sites provide their data in comfortable formats
+ such as ``.csv``.
This is where web scraping comes in. Web scraping is the practice of using
computer program to sift through a web page and gather the data that you need
@@ -18,8 +18,8 @@ lxml
----
`lxml `_ is a pretty extensive library written for parsing
-XML and HTML documents, which you can easily install using `pip`. We will
-be using its `html` module to get data from this web page: `econpy '_ .
+XML and HTML documents, which you can easily install using ``pip``. We will
+be using its `html` module to get data from this web page: `econpy `_ .
First we shall import the required modules:
@@ -28,8 +28,8 @@ First we shall import the required modules:
from lxml import html
from urllib2 import urlopen
-We will use `urllib2.urlopen` to retrieve the web page with our data and
-parse it using the `html` module:
+We will use ``urllib2.urlopen`` to retrieve the web page with our data and
+parse it using the ``html`` module:
.. code-block:: python
@@ -39,7 +39,7 @@ parse it using the `html` module:
`tree` now contains the whole HTML file in a nice tree structure which
we can go over in many different ways, one of which is using XPath. XPath
is a way of locating information in structured documents such as HTML or XML
-pages. A good introduction to XPath is 'here '_ .
+pages. A good introduction to XPath is `here `_ .
One can also use various tools for obtaining the XPath of elements such as
FireBug for Firefox or in Chrome you can right click an element, choose
'Inspect element', highlight the code and the right click again and choose
@@ -65,6 +65,7 @@ Lets see what we got exactly:
print 'Prices: ', prices
::
+
Buyers: ['Carson Busses', 'Earl E. Byrd', 'Patty Cakes',
'Derri Anne Connecticut', 'Moe Dess', 'Leda Doggslife', 'Dan Druff',
'Al Fresco', 'Ido Hoe', 'Howie Kisses', 'Len Lease', 'Phil Meup',
From c3d7bddf3d6c0fa8781f7a0e64389abc20e6892a Mon Sep 17 00:00:00 2001
From: sirMackk
Date: Mon, 31 Dec 2012 10:31:08 -0500
Subject: [PATCH 0093/1232] Third, final markup fixes.
---
docs/scenarios/scrape.rst | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/docs/scenarios/scrape.rst b/docs/scenarios/scrape.rst
index b2bd0706f..8fe6e0337 100644
--- a/docs/scenarios/scrape.rst
+++ b/docs/scenarios/scrape.rst
@@ -8,7 +8,7 @@ Web sites are written using HTML, which means that each web page is a
structured document. Sometimes it would be great to obtain some data from
them and preserve the structure while we're at it, but this isn't always easy.
It's not often that web sites provide their data in comfortable formats
- such as ``.csv``.
+such as ``.csv``.
This is where web scraping comes in. Web scraping is the practice of using
computer program to sift through a web page and gather the data that you need
@@ -19,7 +19,7 @@ lxml
`lxml `_ is a pretty extensive library written for parsing
XML and HTML documents, which you can easily install using ``pip``. We will
-be using its `html` module to get data from this web page: `econpy `_ .
+be using its ``html`` module to get example data from this web page: `econpy.org `_ .
First we shall import the required modules:
From 83c9cba2a3ad6c161eb686bd071c625873f4aa32 Mon Sep 17 00:00:00 2001
From: sirMackk
Date: Mon, 31 Dec 2012 10:37:21 -0500
Subject: [PATCH 0094/1232] Added a bit more code to improve understanding.
---
docs/scenarios/scrape.rst | 26 ++++++++++++++++++++------
1 file changed, 20 insertions(+), 6 deletions(-)
diff --git a/docs/scenarios/scrape.rst b/docs/scenarios/scrape.rst
index 8fe6e0337..aa42bccd5 100644
--- a/docs/scenarios/scrape.rst
+++ b/docs/scenarios/scrape.rst
@@ -36,10 +36,13 @@ parse it using the ``html`` module:
page = urlopen('http://econpy.pythonanywhere.com/ex/001.html')
tree = html.fromstring(page.read())
-`tree` now contains the whole HTML file in a nice tree structure which
-we can go over in many different ways, one of which is using XPath. XPath
-is a way of locating information in structured documents such as HTML or XML
-pages. A good introduction to XPath is `here `_ .
+``tree`` now contains the whole HTML file in a nice tree structure which
+we can go over two different ways: XPath and CSSSelect. In this example, I
+will focus on the former.
+
+XPath is a way of locating information in structured documents such as
+HTML or XML pages. A good introduction to XPath is `here `_ .
+
One can also use various tools for obtaining the XPath of elements such as
FireBug for Firefox or in Chrome you can right click an element, choose
'Inspect element', highlight the code and the right click again and choose
@@ -47,8 +50,15 @@ FireBug for Firefox or in Chrome you can right click an element, choose
After a quick analysis, we see that in our page the data is contained in
two elements - one is a div with title 'buyer-name' and the other is a
-span with class 'item-price'. Knowing this we can create the correct XPath
-query and use the lxml `xpath` function like this:
+span with class 'item-price':
+
+.. code-bloc:: html
+
+ Carson Busses
+ $29.95
+
+Knowing this we can create the correct XPath query and use the lxml
+``xpath`` function like this:
.. code-block:: python
@@ -81,3 +91,7 @@ Congratulations! We have successfully scraped all the data we wanted from
a web page using lxml and we have it stored in memory as two lists. Now we
can either continue our work on it, analyzing it using python or we can
export it to a file and share it with friends.
+
+A cool idea to think about is writing a script to iterate through the rest
+of the pages of this example data set or making this application use
+threads to improve its speed.
From a22a6e92fa7c60bf6673a6c8b1b1bb9d6a4ec4bb Mon Sep 17 00:00:00 2001
From: sirMackk
Date: Mon, 31 Dec 2012 10:39:25 -0500
Subject: [PATCH 0095/1232] Fixing html code-block
---
docs/scenarios/scrape.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/scenarios/scrape.rst b/docs/scenarios/scrape.rst
index aa42bccd5..ca7a44ee6 100644
--- a/docs/scenarios/scrape.rst
+++ b/docs/scenarios/scrape.rst
@@ -52,7 +52,7 @@ After a quick analysis, we see that in our page the data is contained in
two elements - one is a div with title 'buyer-name' and the other is a
span with class 'item-price':
-.. code-bloc:: html
+::
Carson Busses
$29.95
From 32dea94b808925ff9104fec1ba489ecef49cc838 Mon Sep 17 00:00:00 2001
From: sirMackk
Date: Mon, 31 Dec 2012 17:16:00 -0500
Subject: [PATCH 0096/1232] Using requests instead of urllib2, final draft.
---
docs/scenarios/scrape.rst | 22 ++++++++++++----------
1 file changed, 12 insertions(+), 10 deletions(-)
diff --git a/docs/scenarios/scrape.rst b/docs/scenarios/scrape.rst
index ca7a44ee6..e7333c0fd 100644
--- a/docs/scenarios/scrape.rst
+++ b/docs/scenarios/scrape.rst
@@ -14,27 +14,29 @@ This is where web scraping comes in. Web scraping is the practice of using
computer program to sift through a web page and gather the data that you need
in a format most useful to you.
-lxml
-----
+lxml and Requests
+-----------------
`lxml `_ is a pretty extensive library written for parsing
-XML and HTML documents, which you can easily install using ``pip``. We will
-be using its ``html`` module to get example data from this web page: `econpy.org `_ .
+XML and HTML documents really fast. It even handles messed up tags. We will
+also be using the `Requests `_ module instead of the already built-in urlib2
+due to improvements in speed and readability. You can easily install both
+using ``pip install lxml`` and ``pip install requests``.
-First we shall import the required modules:
+Lets start with the imports:
.. code-block:: python
from lxml import html
- from urllib2 import urlopen
+ import requests
-We will use ``urllib2.urlopen`` to retrieve the web page with our data and
-parse it using the ``html`` module:
+Next we will use ``requests.get`` to retrieve the web page with our data
+and parse it using the ``html`` module and save the results in ``tree``:
.. code-block:: python
- page = urlopen('http://econpy.pythonanywhere.com/ex/001.html')
- tree = html.fromstring(page.read())
+ page = requests.get('http://econpy.pythonanywhere.com/ex/001.html')
+ tree = html.fromstring(page.text)
``tree`` now contains the whole HTML file in a nice tree structure which
we can go over two different ways: XPath and CSSSelect. In this example, I
From aa7f9aac98faa1d4c86cce8fa0e60a56ab5e6d6d Mon Sep 17 00:00:00 2001
From: sirMackk
Date: Mon, 31 Dec 2012 17:25:34 -0500
Subject: [PATCH 0097/1232] Final version
---
docs/scenarios/scrape.rst | 32 ++++++++++++++++----------------
1 file changed, 16 insertions(+), 16 deletions(-)
diff --git a/docs/scenarios/scrape.rst b/docs/scenarios/scrape.rst
index e7333c0fd..17a028129 100644
--- a/docs/scenarios/scrape.rst
+++ b/docs/scenarios/scrape.rst
@@ -6,13 +6,13 @@ Web Scraping
Web sites are written using HTML, which means that each web page is a
structured document. Sometimes it would be great to obtain some data from
-them and preserve the structure while we're at it, but this isn't always easy.
-It's not often that web sites provide their data in comfortable formats
-such as ``.csv``.
+them and preserve the structure while we're at it. Web sites provide
+don't always provide their data in comfortable formats such as ``.csv``.
-This is where web scraping comes in. Web scraping is the practice of using
+This is where web scraping comes in. Web scraping is the practice of using a
computer program to sift through a web page and gather the data that you need
-in a format most useful to you.
+in a format most useful to you while at the same time preserving the structure
+of the data.
lxml and Requests
-----------------
@@ -43,12 +43,12 @@ we can go over two different ways: XPath and CSSSelect. In this example, I
will focus on the former.
XPath is a way of locating information in structured documents such as
-HTML or XML pages. A good introduction to XPath is `here `_ .
+HTML or XML documents. A good introduction to XPath is on `W3Schools `_ .
-One can also use various tools for obtaining the XPath of elements such as
-FireBug for Firefox or in Chrome you can right click an element, choose
-'Inspect element', highlight the code and the right click again and choose
-'Copy XPath'.
+There are also various tools for obtaining the XPath of elements such as
+FireBug for Firefox or if you're using Chrome you can right click an
+element, choose 'Inspect element', highlight the code and then right
+click again and choose 'Copy XPath'.
After a quick analysis, we see that in our page the data is contained in
two elements - one is a div with title 'buyer-name' and the other is a
@@ -90,10 +90,10 @@ Lets see what we got exactly:
'$15.00', '$114.07', '$10.09']
Congratulations! We have successfully scraped all the data we wanted from
-a web page using lxml and we have it stored in memory as two lists. Now we
-can either continue our work on it, analyzing it using python or we can
-export it to a file and share it with friends.
+a web page using lxml and Requests. We have it stored in memory as two
+lists. Now we can do all sorts of cool stuff with it: we can analyze it
+using Python or we can save it a file and share it with the world.
-A cool idea to think about is writing a script to iterate through the rest
-of the pages of this example data set or making this application use
-threads to improve its speed.
+A cool idea to think about is modifying this script to iterate through
+the rest of the pages of this example dataset or rewriting this
+application to use threads for improved speed.
From 629626a66d4ddedbe4be546248070944026895f0 Mon Sep 17 00:00:00 2001
From: Kenneth Reitz
Date: Mon, 31 Dec 2012 17:59:47 -0500
Subject: [PATCH 0098/1232] Update docs/conf.py
---
docs/conf.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/conf.py b/docs/conf.py
index 9616262c2..04c0a5fa1 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -46,7 +46,7 @@
# General information about the project.
project = u'pythonguide'
-copyright = u'2012. A Kenneth Reitz Project. Creative Commons Share-Alike 3.0.'
+copyright = u'2013. A Kenneth Reitz Project. Creative Commons Share-Alike 3.0.'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
From d3218d431eda874dc6c8c45a85c09333cc6f7b0c Mon Sep 17 00:00:00 2001
From: Kenneth Reitz
Date: Wed, 2 Jan 2013 19:09:29 -0500
Subject: [PATCH 0099/1232] Update docs/index.rst
---
docs/index.rst | 7 +++----
1 file changed, 3 insertions(+), 4 deletions(-)
diff --git a/docs/index.rst b/docs/index.rst
index 90cda0898..19e167222 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -6,13 +6,12 @@
The Hitchhiker's Guide to Python!
=================================
-Welcome to The Hitchhiker's Guide to Python. `DON'T PANIC! `_
+Welcome to The Hitchhiker's Guide to Python.
-**This guide is currently under heavy development, and is mostly a skeleton at
-the moment.** If you'd like to help, `fork us on GitHub `_!
+**This guide is currently under heavy active development.** If you'd like to help, `fork us on GitHub `_!
This *opinionated* guide exists to provide both novice and expert Python
developers a best-practice handbook to the installation, configuration, and
usage of Python on a daily basis.
-.. include:: contents.rst.inc
\ No newline at end of file
+.. include:: contents.rst.inc
From 65c5fb6280d7ca2d8da8c56470dae791c1578ffa Mon Sep 17 00:00:00 2001
From: Jeroen Van Goey
Date: Fri, 11 Jan 2013 10:17:50 +0100
Subject: [PATCH 0100/1232] Update docs/writing/style.rst
rpartition() takes a seperator as argument
---
docs/writing/style.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index bd264cef6..c43c45a9a 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -286,7 +286,7 @@ will not need that variable, use ``__``:
.. code-block:: python
filename = 'foobar.txt'
- basename, __, ext = filename.rpartition()
+ basename, __, ext = filename.rpartition('.')
.. note::
From 7990eb8e423d81351e4fd0027fd72b3500bd1cae Mon Sep 17 00:00:00 2001
From: Gongzhi
Date: Fri, 25 Jan 2013 18:07:10 +0800
Subject: [PATCH 0101/1232] fix the typo
nothing more.
---
docs/intro/duction.rst | 176 ++++++++++++++++++++---------------------
1 file changed, 88 insertions(+), 88 deletions(-)
diff --git a/docs/intro/duction.rst b/docs/intro/duction.rst
index e0d4180bc..fdebc18d8 100644
--- a/docs/intro/duction.rst
+++ b/docs/intro/duction.rst
@@ -1,88 +1,88 @@
-Introduction
-============
-
-From the `official Python website `_:
-
-Python is a general-purpose, high-level programming language similar
-to Tcl, Perl, Ruby, Scheme, or Java. Some of its main key features
-include:
-
-* very clear, readable syntax
-
- Python's philosophy focuses on readability, from code blocks
- delineated with significant whitespace to intuitive keywords in
- place of inscrutable punctuation
-
-* extensive standard libraries and third party modules for virtually
- any task
-
- Python is sometimes described with the words "batteries included"
- for its extensive
- `standard library `_, which can
- includes modules for regular expressions, file IO, fraction handling,
- object serialization, and much more.
-
- Additionally, the
- `Python Package Index `_ is available
- for users to submit their packages for widespread use, similar to
- Perl's `CPAN `_. There is a thriving community
- of very powerful Python frameworks and tools like
- the `Django `_ web framework and the
- `NumPy `_ set of math routines.
-
-* integration with other systems
-
- Python can integrate with `Java libraries `_,
- enabling it to be used with the rich Java environment that corporate
- programmers are used to. It can also be
- `extended by C or C++ modules `_
- when speed is of the essence.
-
-* ubiquity on computers
-
- Python is available on Windows, \*nix, and Mac. It runs wherever the
- Java virtual machine runs, and the reference implementation CPython
- can help bring Python to wherever there is a working C compiler.
-
-* friendly community
-
- Python has a vibrant and large :ref:`community `
- which maintains wikis, conferences, countless repositories,
- mailing lists, IRC channels, and so much more. Heck, the Python
- community is even helping to write this guide!
-
-
-.. _about-ref:
-
-About This Guide
-----------------
-
-Purpose
-~~~~~~~
-
-The Hitchhiker's Guide to Python exists to provide both novice and expert
-Python developers a best-practice handbook to the installation, configuration,
-and usage of Python on a daily basis.
-
-
-By the Community
-~~~~~~~~~~~~~~~~
-
-This guide is architected and maintained by `Kenneth Reitz
-`_ in an open fashion. This is a
-community-driven effort that serves one purpose: to serve the community.
-
-For the Community
-~~~~~~~~~~~~~~~~~
-
-All contributions to the Guide are welcome, from Pythonistas of all levels.
-If you think there's a gap in what the Guide covers, fork the Guide on
-GitHub and submit a pull request. Contributions are welcome from everyone,
-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
-appropriateness, completeness, or accuracy of a contribution.
-
-To get started working on The Hitchhiker's Guide, see
-the :doc:`/notes/contribute` page.
-
-
+Introduction
+============
+
+From the `official Python website `_:
+
+Python is a general-purpose, high-level programming language similar
+to Tcl, Perl, Ruby, Scheme, or Java. Some of its main key features
+include:
+
+* very clear, readable syntax
+
+ Python's philosophy focuses on readability, from code blocks
+ delineated with significant whitespace to intuitive keywords in
+ place of inscrutable punctuation
+
+* extensive standard libraries and third party modules for virtually
+ any task
+
+ Python is sometimes described with the words "batteries included"
+ for its extensive
+ `standard library `_, which can
+ includes modules for regular expressions, file IO, fraction handling,
+ object serialization, and much more.
+
+ Additionally, the
+ `Python Package Index `_ is available
+ for users to submit their packages for widespread use, similar to
+ Perl's `CPAN `_. There is a thriving community
+ of very powerful Python frameworks and tools like
+ the `Django `_ web framework and the
+ `NumPy `_ set of math routines.
+
+* integration with other systems
+
+ Python can integrate with `Java libraries `_,
+ enabling it to be used with the rich Java environment that corporate
+ programmers are used to. It can also be
+ `extended by C or C++ modules `_
+ when speed is of the essence.
+
+* ubiquity on computers
+
+ Python is available on Windows, \*nix, and Mac. It runs wherever the
+ Java virtual machine runs, and the reference implementation CPython
+ can help bring Python to wherever there is a working C compiler.
+
+* friendly community
+
+ Python has a vibrant and large :ref:`community `
+ which maintains wikis, conferences, countless repositories,
+ mailing lists, IRC channels, and so much more. Heck, the Python
+ community is even helping to write this guide!
+
+
+.. _about-ref:
+
+About This Guide
+----------------
+
+Purpose
+~~~~~~~
+
+The Hitchhiker's Guide to Python exists to provide both novice and expert
+Python developers a best-practice handbook to the installation, configuration,
+and usage of Python on a daily basis.
+
+
+By the Community
+~~~~~~~~~~~~~~~~
+
+This guide is architected and maintained by `Kenneth Reitz
+`_ in an open fashion. This is a
+community-driven effort that serves one purpose: to serve the community.
+
+For the Community
+~~~~~~~~~~~~~~~~~
+
+All contributions to the Guide are welcome, from Pythonistas of all levels.
+If you think there's a gap in what the Guide covers, fork the Guide on
+GitHub and submit a pull request. Contributions are welcome from everyone,
+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
+appropriateness, completeness, or accuracy of a contribution.
+
+To get started working on The Hitchhiker's Guide, see
+the: doc:`/notes/contribute` page.
+
+
From 7d22f84ff91f82d26c55c86c194c4e7e8a2b2b0a Mon Sep 17 00:00:00 2001
From: David Echols
Date: Sat, 26 Jan 2013 11:42:42 -0800
Subject: [PATCH 0102/1232] Added new Reading section.
If readability is so important to python, why don't python guides have a
list of recommended awesome code to read? Why don't they explain that
code? The idea behind this reading section is to provide such a guide.
The idea here is to start with something small and useful, with a vision
for the future, and iterate quickly.
---
docs/contents.rst.inc | 237 ++++----
docs/writing/reading.rst | 44 ++
docs/writing/style.rst | 1227 +++++++++++++++++++-------------------
3 files changed, 777 insertions(+), 731 deletions(-)
create mode 100644 docs/writing/reading.rst
diff --git a/docs/contents.rst.inc b/docs/contents.rst.inc
index a1663c667..679380d2b 100644
--- a/docs/contents.rst.inc
+++ b/docs/contents.rst.inc
@@ -1,118 +1,119 @@
-Getting Started
----------------
-
-This part of the guide focuses on setting up your Python environment.
-
-.. toctree::
- :maxdepth: 2
-
- starting/which-python
-
-- Properly Install Python
-
- .. toctree::
- :maxdepth: 1
-
- starting/install/osx
- starting/install/win
- starting/install/linux
-
-
-
-Writing Great Code
-------------------
-
-This part of the guide focuses on best practices for writing Python code.
-
-.. toctree::
- :maxdepth: 2
-
- writing/structure
- writing/style
- writing/documentation
- writing/tests
- writing/gotchas
- writing/license
-
-
-
-Scenario Guide
---------------
-
-This part of the guide focuses on tool and module advice based on
-different scenarios.
-
-.. toctree::
- :maxdepth: 2
-
- scenarios/client
- scenarios/web
- scenarios/cli
- scenarios/gui
- scenarios/db
- scenarios/network
- scenarios/admin
- scenarios/ci
- scenarios/speed
- scenarios/scientific
- scenarios/imaging
- scenarios/xml
-
-
-Shipping Great Code
--------------------
-
-This part of the guide focuses on deploying your Python code.
-
-.. toctree::
- :maxdepth: 2
-
- shipping/packaging
- shipping/freezing
-
-
-Development Environment
------------------------
-
-.. toctree::
- :maxdepth: 2
-
- dev/env
- dev/virtualenvs
-
-
-
-
-Additional Notes
-----------------
-
-This part of the guide, which is mostly prose, begins with some
-background information about Python, then focuses on next steps.
-
-.. toctree::
- :maxdepth: 2
-
- intro/duction
- intro/community
- intro/learning
- intro/documentation
- intro/news
-
-
-
-
---------------------------------------
-
-Contribution notes and legal information are here (for those interested).
-
-.. toctree::
- :maxdepth: 2
-
- notes/contribute
- notes/license
- notes/styleguide
-
-
-
-
-
+Getting Started
+---------------
+
+This part of the guide focuses on setting up your Python environment.
+
+.. toctree::
+ :maxdepth: 2
+
+ starting/which-python
+
+- Properly Install Python
+
+ .. toctree::
+ :maxdepth: 1
+
+ starting/install/osx
+ starting/install/win
+ starting/install/linux
+
+
+
+Writing Great Code
+------------------
+
+This part of the guide focuses on best practices for writing Python code.
+
+.. toctree::
+ :maxdepth: 2
+
+ writing/structure
+ writing/style
+ writing/reading
+ writing/documentation
+ writing/tests
+ writing/gotchas
+ writing/license
+
+
+
+Scenario Guide
+--------------
+
+This part of the guide focuses on tool and module advice based on
+different scenarios.
+
+.. toctree::
+ :maxdepth: 2
+
+ scenarios/client
+ scenarios/web
+ scenarios/cli
+ scenarios/gui
+ scenarios/db
+ scenarios/network
+ scenarios/admin
+ scenarios/ci
+ scenarios/speed
+ scenarios/scientific
+ scenarios/imaging
+ scenarios/xml
+
+
+Shipping Great Code
+-------------------
+
+This part of the guide focuses on deploying your Python code.
+
+.. toctree::
+ :maxdepth: 2
+
+ shipping/packaging
+ shipping/freezing
+
+
+Development Environment
+-----------------------
+
+.. toctree::
+ :maxdepth: 2
+
+ dev/env
+ dev/virtualenvs
+
+
+
+
+Additional Notes
+----------------
+
+This part of the guide, which is mostly prose, begins with some
+background information about Python, then focuses on next steps.
+
+.. toctree::
+ :maxdepth: 2
+
+ intro/duction
+ intro/community
+ intro/learning
+ intro/documentation
+ intro/news
+
+
+
+
+--------------------------------------
+
+Contribution notes and legal information are here (for those interested).
+
+.. toctree::
+ :maxdepth: 2
+
+ notes/contribute
+ notes/license
+ notes/styleguide
+
+
+
+
+
diff --git a/docs/writing/reading.rst b/docs/writing/reading.rst
new file mode 100644
index 000000000..4ab1ddba1
--- /dev/null
+++ b/docs/writing/reading.rst
@@ -0,0 +1,44 @@
+Reading Great Code
+==================
+
+One of the core tenants behind the design of Python is creating
+readable code. The motivation behind this design is simple: The number
+one thing that Python programmers do is read code.
+
+One of the secrets of becoming a great Python programmer is to read,
+understand, and comprehend excellent code.
+
+Excellent code typically follows the guidelines outlined in :ref:`code_style`,
+and does its best to express a clear and consise intent to the reader.
+
+Included below is a list of recommended Python projects for reading. Each of
+these projects are paragons of excellent Python code.
+
+- `Howdoi `_
+ Howdoi is a code search tool, written in Python.
+
+- `Flask `_
+ Flask is a microframework for Python based on Werkzeug and Jinja2.
+ It's intended for getting started very quickly and was developed with
+ best intentions in mind.
+
+- `Werkzeug `_
+ Werkzeug started as simple collection of various utilities for WSGI
+ applications and has become one of the most advanced WSGI utility modules.
+ It includes a powerful debugger, full-featured request and response objects,
+ HTTP utilities to handle entity tags, cache control headers, HTTP dates,
+ cookie handling, file uploads, a powerful URL routing system and a bunch
+ of community-contributed addon modules.
+
+- `Requests `_
+ Requests is an Apache2 Licensed HTTP library, written in Python,
+ for human beings.
+
+- `Tablib `_
+ Tablib is a format-agnostic tabular dataset library, written in Python.
+
+.. todo:: Embed and explain YouTube video showing python code reading: http://www.youtube.com/watch?v=Jc8M9-LoEuo This may require installing a Sphinx plugin. https://bitbucket.org/birkenfeld/sphinx-contrib/src/a09f29fc16970f34350ca36ac7f229e00b1b1674/youtube?at=default
+
+.. todo:: Include code examples of exemplary code from each of the projects listed. Explain why it is excellent code. Use complex examples.
+
+.. todo:: Explain techniques to rapidly identify data structures, algorithms and determine what the code is doing.
\ No newline at end of file
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index c43c45a9a..919d3a147 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -1,613 +1,614 @@
-Code Style
-==========
-
-If you ask Python programmers what they like most in Python, they will
-often say its high readability. Indeed, a high level of readability
-is at the heart of the design of the Python language, following the
-recognised fact that code is read much more often than it is written.
-
-One reason for Python code to be easily read and understood is its relatively
-complete set of Code Style guidelines and "Pythonic" idioms.
-
-Moreover, when a veteran Python developer (a Pythonista) point to some
-parts of a code and say it is not "Pythonic", it usually means that these lines
-of code do not follow the common guidelines and fail to express the intent in
-what is considered the best (hear: most readable) way.
-
-On some border cases, no best way has been agreed upon on how to express
-an intent in Python code, but these cases are rare.
-
-General concepts
-----------------
-
-Explicit code
-~~~~~~~~~~~~~
-
-While any kind of black magic is possible with Python, the
-most explicit and straightforward manner is preferred.
-
-**Bad**
-
-.. code-block:: python
-
- def make_complex(*args):
- x, y = args
- return dict(**locals())
-
-**Good**
-
-.. code-block:: python
-
- def make_complex(x, y):
- return {'x': x, 'y': y}
-
-In the good code above, x and y are explicitly received from
-the caller, and an explicit dictionary is returned. The developer
-using this function knows exactly what to do by reading the
-first and last lines, which is not the case with the bad example.
-
-One statement per line
-~~~~~~~~~~~~~~~~~~~~~~
-
-While some compound statements such as list comprehensions are
-allowed and appreciated for their brevity and their expressiveness,
-it is bad practice to have two disjoint statements on the same line.
-
-**Bad**
-
-.. code-block:: python
-
- print 'one'; print 'two'
-
- if x == 1: print 'one'
-
- if and :
- # do something
-
-**Good**
-
-.. code-block:: python
-
- print 'one'
- print 'two'
-
- if x == 1:
- print 'one'
-
- cond1 =
- cond2 =
- if cond1 and cond2:
- # do something
-
-Function arguments
-~~~~~~~~~~~~~~~~~~
-
-Arguments can be passed to functions in four different ways.
-
-**Positional arguments** are mandatory and have no default values. They are the
-simplest form of arguments and they can be used for the few function arguments
-that are fully part of the functions meaning and their order is natural. For
-instance, in ``send(message, recipient)`` or ``point(x, y)`` the user of the
-function has no difficulty to remember that those two function require two
-arguments, and in which order.
-
-In those two cases, it is possible to use argument names when calling the functions
-and, doing so, it is possible to switch the order of arguments, calling for instance
-``send(recipient='World', message='Hello')`` and ``point(y=2, x=1)`` but this
-reduce readability and is unnecessarily verbose, compared to the more straightforward
-calls to ``send('Hello', 'World')`` and ``point(1, 2)``.
-
-**Keyword arguments** are not mandatory and have default values. They are often
-used for optional parameters sent to the function. When a function has more than
-two or three positional parameters, its signature will be more difficult to remember
-and using keyword argument with default values is helpful. For instance, a more
-complete ``send`` function could be defined as ``send(message, to, cc=None, bcc=None)``.
-Here ``cc`` and ``bcc`` are optional, and evaluate to ``None`` when the are not
-passed another value.
-
-Calling a function with keyword arguments can be done in multiple ways in Python,
-for example it is possible to follow the order of arguments in the definition without
-explicitly naming the arguments, like in ``send('Hello', 'World', 'Cthulhu', 'God')``,
-sending a blank carbon copy to God. It would also be possible to name arguments in
-another order, like in ``send('Hello again', 'World', bcc='God', cc='Cthulhu')``.
-Those two possibilities are better avoided without any strong reason to not
-follow the syntax that is the closest to the function definition: ``send('Hello',
-'World', cc='Cthulhu', bcc='God')``.
-
-As a side note, following `YAGNI `_
-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
-new optional argument and its logic when needed.
-
-The **arbitrary argument list** is the third way to pass arguments to a
-function. If the function intention is better expressed by a signature with an
-extensible number of positional arguments, it can be defined with the ``*args``
-constructs. In the function body, ``args`` will be a tuple of all the
-remaining positional arguments. For example, ``send(message, *args)`` can be
-called with each recipient as an argument: ``send('Hello', 'God', 'Mom',
-'Cthulhu')``, and in the function body ``args`` will be equal to ``('God',
-'Mom', 'Cthulhu')``.
-
-However, this construct has some drawbacks and should be used with caution. If a
-function receives a list of arguments of the same nature, it is often more
-clear to define it as a function of one argument, that argument being a list or
-any sequence. Here, if ``send`` has multiple recipients, it is better to define
-it explicitly: ``send(message, recipients)`` and call it with ``send('Hello',
-['God', 'Mom', 'Cthulhu'])``. This way, the user of the function can manipulate
-the recipient list as a list beforehand, and it opens the possibility to pass
-any sequence, including iterators, that cannot be unpacked as other sequences.
-
-The **arbitrary keyword argument dictionary** is the last way to pass arguments
-to functions. If the function requires an undetermined series of named
-arguments, it is possible to used the ``**kwargs`` construct. In the function
-body, ``kwargs`` will be a dictionary of all the passed named arguments that
-have not been caught be other keyword argument in the function signature.
-
-The same caution as in the case of *arbitrary argument list* is necessary, for
-similar reasons: these powerful techniques are to be used when there is a
-proven necessity to use them, and they should not be used if the simpler and
-clearer construct is sufficient to express the function's intention.
-
-It is up to the programmer writing the function to determine which arguments
-are positional arguments and which are optional keyword arguments, and to
-decide whether to use the advanced techniques of arbitrary argument passing. If
-the advice above is followed wisely, it is possible and enjoyable to write
-Python functions that are:
-
-* easy to read (the name and arguments need no explanations)
-
-* easy to change (adding a new keyword argument does not break other parts of the
- code)
-
-Avoid the magical wand
-~~~~~~~~~~~~~~~~~~~~~~
-
-A powerful tool for hackers, Python comes with a very rich set of hooks and
-tools allowing to do almost any kind of tricky tricks. For instance, it is
-possible to change how objects are created and instantiated, it is possible to
-change how the Python interpreter imports modules, it is even possible (and
-recommended if needed) to embed C routines in Python.
-
-However, all these options have many drawbacks and it is always better to use
-the most straightforward way to achieve your goal. The main drawback is that
-readability suffers deeply from them. Many code analysis tools, such as pylint
-or pyflakes, will be unable to parse this "magic" code.
-
-We consider that a Python developer should know about these nearly infinite
-possibilities, because it grows the confidence that no hard-wall will be on the
-way. However, knowing how to use them and particularly when **not** to use
-them is the most important.
-
-Like a Kungfu master, a Pythonista knows how to kill with a single finger, and
-never to do it.
-
-We are all consenting adults
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-As seen above, Python allows many tricks, and some of them are potentially
-dangerous. A good example is that any client code can override an object's
-properties and methods: there is no "private" keyword in Python. This
-philosophy, very different from highly defensive languages like Java, which
-give a lot of mechanism to prevent any misuse, is expressed by the saying: "We
-are consenting adults".
-
-This doesn't mean that, for example, no properties are considered private, and
-that no proper encapsulation is possible in Python. But, instead of relying on
-concrete walls erected by the developers between their code and other's, the
-Python community prefers to rely on a set of convention indicating that these
-elements should not be accessed directly.
-
-The main convention for private properties and implementation details is to
-prefix all "internals" with an underscore. If the client code breaks this rule
-and access to these marked elements, any misbehavior or problems encountered if
-the code is modified is the responsibility of the client code.
-
-Using this convention generously is encouraged: any method or property that is
-not intended to be used by client code should be prefixed with an underscore.
-This will guarantee a better separation of duties and easier modifications of
-existing code, and it will always be possible to publicize a private property,
-while privatising a public property might be a much harder operation.
-
-Returning values
-~~~~~~~~~~~~~~~~
-
-When a function grows in complexity is not uncommon to use multiple return statements
-inside the function's body. However, in order to keep a clear intent and a sustainable
-readability level, it is preferable to avoid returning meaningful values from many
-output point in the body.
-
-There are two main cases for returning values in a function: The result of the function
-return when it has been processed normally, and the error cases that indicate a wrong
-input parameter or any other reason for the function to not be able to complete its
-computation or task.
-
-If you do not wish to raise exceptions for the second case, then returning a value, such
-as None or False, indicating that the function could not perform correctly might be needed. In this
-case, it is better to return as early as the incorrect context has been detected. It will
-help to flatten the structure of the function: all the code after the return-because-of-error
-statement can assume the condition is met to further compute the function's main result.
-Having multiple such return statement is often necessary.
-
-However, when a function has multiple main exit points for its normal course, it becomes
-difficult to debug the returned result, and it may be preferable to keep a single exit
-point. This will also help factoring out some code paths, and the multiple exit point
-is a probable indication that such a refactoring is needed.
-
-.. code-block:: python
-
- def complex_function(a, b, c):
- if not a:
- return None # Raising an exception might be better
- if not b:
- return None # Raising an exception might be better
- # Some complex code trying to compute x from a, b and c
- # Resist temptation to return x if succeeded
- if not x:
- # Some Plan-B computation of x
- return x # One single exit point for the returned value x will help
- # when maintaining the code.
-
-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
-
-Nested unpacking works too:
-
-.. code-block:: python
-
- a, (b, c) = 1, (2, 3)
-
-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('.')
-
-.. note::
-
- Many Python style guides recommend the use of a single underscore "``_``"
- for throwaway variables rather than the double underscore "``__``"
- recommended here. The issue is that "``_``" is commonly used as an alias
- for the :func:`~gettext.gettext` function, and is also used at the
- interactive prompt to hold the value of the last operation. Using a
- double underscore instead is just as clear and almost as convenient,
- and eliminates the risk of accidentally interfering with either of
- these other use cases.
-
-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)]
-
-
-A common idiom for creating strings is to use `join `_ on an empty string.::
-
- letters = ['s', 'p', 'a', 'm']
- word = ''.join(letters)
-
-This will set the value of the variable *word* to 'spam'. This idiom can be applied to lists and tuples.
-
-Sometimes we need to search through a collection of things. Let's look at two options: lists and dictionaries.
-
-Take the following code for example::
-
- d = {'s': [], 'p': [], 'a': [], 'm': []}
- l = ['s', 'p', 'a', 'm']
-
- def lookup_dict(d):
- return 's' in d
-
- def lookup_list(l):
- return 's' in l
-
-Even though both functions look identical, because *lookup_dict* is utilizing the fact that dictionaries in python are hashtables, the lookup performance between the two is very different.
-Python will have to go through each item in the list to find a matching case, which is time consuming. By analysing the hash of the dictionary finding keys in the dict can be done very quickly.
-For more information see this `StackOverflow `_ page.
-
-Zen of Python
--------------
-
-Also known as PEP 20, the guiding principles for Python's design.
-
-::
-
- >>> import this
- The Zen of Python, by Tim Peters
-
- Beautiful is better than ugly.
- Explicit is better than implicit.
- Simple is better than complex.
- Complex is better than complicated.
- Flat is better than nested.
- Sparse is better than dense.
- Readability counts.
- Special cases aren't special enough to break the rules.
- Although practicality beats purity.
- Errors should never pass silently.
- Unless explicitly silenced.
- In the face of ambiguity, refuse the temptation to guess.
- There should be one-- and preferably only one --obvious way to do it.
- Although that way may not be obvious at first unless you're Dutch.
- Now is better than never.
- Although never is often better than *right* now.
- If the implementation is hard to explain, it's a bad idea.
- If the implementation is easy to explain, it may be a good idea.
- Namespaces are one honking great idea -- let's do more of those!
-
-For some examples of good Python style, see `this Stack Overflow question
-`_ or `these
-slides from a Python user group
-`_.
-
-PEP 8
------
-
-PEP 8 is the de-facto code style guide for Python.
-
- `PEP 8 `_
-
-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
-exists a command-line program, `pep8 `_,
-that can check your code for conformance. Install it by running the following
-command in your Terminal:
-
-::
-
- $ pip install pep8
-
-
-Then run it on a file or series of files to get a report of any violations.
-
-::
-
- $ pep8 optparse.py
- optparse.py:69:11: E401 multiple imports on one line
- optparse.py:77:1: E302 expected 2 blank lines, found 1
- optparse.py:88:5: E301 expected 1 blank line, found 0
- optparse.py:222:34: W602 deprecated form of raising exception
- optparse.py:347:31: E211 whitespace before '('
- optparse.py:357:17: E201 whitespace after '{'
- optparse.py:472:29: E221 multiple spaces before operator
- optparse.py:544:21: W601 .has_key() is deprecated, use 'in'
-
-Conventions
-----------------
-
-Here are some conventions you should follow to make your code easier to read.
-
-Check if variable equals a constant
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-You don't need to explicitly compare a value to True, or None, or 0 - you can
-just add it to the if statement. See `Truth Value Testing
-`_ for a
-list of what is considered false.
-
-**Bad**:
-
-.. code-block:: python
-
- if attr == True:
- print 'True!'
-
- if attr == None:
- print 'attr is None!'
-
-**Good**:
-
-.. code-block:: python
-
- # Just check the value
- if attr:
- print 'attr is truthy!'
-
- # or check for the opposite
- if not attr:
- print 'attr is falsey!'
-
- # or, since None is considered false, explicity check for it
- if attr is None:
- print 'attr is None!'
-
-Access a Dictionary Element
-~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Don't use the ``has_key`` function. Instead use ``x in d`` syntax, or pass
-a default argument to ``get``.
-
-**Bad**:
-
-.. code-block:: python
-
- d = {'hello': 'world'}
- if d.has_key('hello'):
- print d['hello'] # prints 'world'
- else:
- print 'default_value'
-
-**Good**:
-
-.. code-block:: python
-
- d = {'hello': 'world'}
-
- print d.get('hello', 'default_value') # prints 'world'
- print d.get('thingy', 'default_value') # prints 'default_value'
-
- # Or:
- if 'hello' in d:
- print d['hello']
-
-Short Ways to Manipulate Lists
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-`List comprehensions
-`_
-provide a powerful, concise way to work with lists. Also, the `map
-`_ and `filter
-`_ functions can perform
-operations on lists using a different concise syntax.
-
-**Bad**:
-
-.. code-block:: python
-
- # Filter elements greater than 4
- a = [3, 4, 5]
- b = []
- for i in a:
- if i > 4:
- b.append(i)
-
-**Good**:
-
-.. code-block:: python
-
- b = [i for i in a if i > 4]
- b = filter(lambda x: x > 4, a)
-
-**Bad**:
-
-.. code-block:: python
-
- # Add three to all list members.
- a = [3, 4, 5]
- count = 0
- for i in a:
- a[count] = i + 3
- count = count + 1
-
-**Good**:
-
-.. code-block:: python
-
- a = [3, 4, 5]
- a = [i + 3 for i in a]
- # Or:
- a = map(lambda i: i + 3, a)
-
-Use `enumerate `_ to
-keep a count of your place in the list.
-
-.. code-block:: python
-
- for i, item in enumerate(a):
- print i + ", " + item
- # prints
- # 0, 3
- # 1, 4
- # 2, 5
-
-The ``enumerate`` function has better readability than handling a counter
-manually. Moreover,
-it is better optimized for iterators.
-
-Read From a File
-~~~~~~~~~~~~~~~~
-
-Use the ``with open`` syntax to read from files. This will automatically close
-files for you.
-
-**Bad**:
-
-.. code-block:: python
-
- f = open('file.txt')
- a = f.read()
- print a
- f.close()
-
-**Good**:
-
-.. code-block:: python
-
- with open('file.txt') as f:
- for line in f:
- print line
-
-The ``with`` statement is better because it will ensure you always close the
-file, even if an exception is raised.
-
-Line Continuations
-~~~~~~~~~~~~~~~~~~
-
-When a logical line of code is longer than the accepted limit, you need to
-split it over multiple physical lines. Python interpreter will join consecutive
-lines if the last character of the line is a backslash. This is helpful
-sometime but is preferably avoided, because of its fragility: a white space
-added to the end of the line, after the backslash, will break the code and may
-have unexpected results.
-
-A preferred solution is to use parenthesis around your elements. Left with an
-unclosed parenthesis on an end-of-line the Python interpreter will join the
-next line until the parenthesis is closed. The same behavior holds for curly
-and square braces.
-
-**Bad**:
-
-.. code-block:: python
-
- my_very_big_string = """For a long time I used to go to bed early. Sometimes, \
- when I had put out my candle, my eyes would close so quickly that I had not even \
- time to say “I’m going to sleep.”"""
-
- from some.deep.module.inside.a.module import a_nice_function, another_nice_function, \
- yet_another_nice_function
-
-**Good**:
-
-.. code-block:: python
-
- my_very_big_string = (
- "For a long time I used to go to bed early. Sometimes, "
- "when I had put out my candle, my eyes would close so quickly "
- "that I had not even time to say “I’m going to sleep.”"
- )
-
- from some.deep.module.inside.a.module import (
- a_nice_function, another_nice_function, yet_another_nice_function)
-
-However, more often than not having to split long logical line is a sign that
-you are trying to do too many things at the same time, which may hinder
-readability.
+.. code_style:
+Code Style
+==========
+
+If you ask Python programmers what they like most in Python, they will
+often say its high readability. Indeed, a high level of readability
+is at the heart of the design of the Python language, following the
+recognised fact that code is read much more often than it is written.
+
+One reason for Python code to be easily read and understood is its relatively
+complete set of Code Style guidelines and "Pythonic" idioms.
+
+Moreover, when a veteran Python developer (a Pythonista) point to some
+parts of a code and say it is not "Pythonic", it usually means that these lines
+of code do not follow the common guidelines and fail to express the intent in
+what is considered the best (hear: most readable) way.
+
+On some border cases, no best way has been agreed upon on how to express
+an intent in Python code, but these cases are rare.
+
+General concepts
+----------------
+
+Explicit code
+~~~~~~~~~~~~~
+
+While any kind of black magic is possible with Python, the
+most explicit and straightforward manner is preferred.
+
+**Bad**
+
+.. code-block:: python
+
+ def make_complex(*args):
+ x, y = args
+ return dict(**locals())
+
+**Good**
+
+.. code-block:: python
+
+ def make_complex(x, y):
+ return {'x': x, 'y': y}
+
+In the good code above, x and y are explicitly received from
+the caller, and an explicit dictionary is returned. The developer
+using this function knows exactly what to do by reading the
+first and last lines, which is not the case with the bad example.
+
+One statement per line
+~~~~~~~~~~~~~~~~~~~~~~
+
+While some compound statements such as list comprehensions are
+allowed and appreciated for their brevity and their expressiveness,
+it is bad practice to have two disjoint statements on the same line.
+
+**Bad**
+
+.. code-block:: python
+
+ print 'one'; print 'two'
+
+ if x == 1: print 'one'
+
+ if and :
+ # do something
+
+**Good**
+
+.. code-block:: python
+
+ print 'one'
+ print 'two'
+
+ if x == 1:
+ print 'one'
+
+ cond1 =
+ cond2 =
+ if cond1 and cond2:
+ # do something
+
+Function arguments
+~~~~~~~~~~~~~~~~~~
+
+Arguments can be passed to functions in four different ways.
+
+**Positional arguments** are mandatory and have no default values. They are the
+simplest form of arguments and they can be used for the few function arguments
+that are fully part of the functions meaning and their order is natural. For
+instance, in ``send(message, recipient)`` or ``point(x, y)`` the user of the
+function has no difficulty to remember that those two function require two
+arguments, and in which order.
+
+In those two cases, it is possible to use argument names when calling the functions
+and, doing so, it is possible to switch the order of arguments, calling for instance
+``send(recipient='World', message='Hello')`` and ``point(y=2, x=1)`` but this
+reduce readability and is unnecessarily verbose, compared to the more straightforward
+calls to ``send('Hello', 'World')`` and ``point(1, 2)``.
+
+**Keyword arguments** are not mandatory and have default values. They are often
+used for optional parameters sent to the function. When a function has more than
+two or three positional parameters, its signature will be more difficult to remember
+and using keyword argument with default values is helpful. For instance, a more
+complete ``send`` function could be defined as ``send(message, to, cc=None, bcc=None)``.
+Here ``cc`` and ``bcc`` are optional, and evaluate to ``None`` when the are not
+passed another value.
+
+Calling a function with keyword arguments can be done in multiple ways in Python,
+for example it is possible to follow the order of arguments in the definition without
+explicitly naming the arguments, like in ``send('Hello', 'World', 'Cthulhu', 'God')``,
+sending a blank carbon copy to God. It would also be possible to name arguments in
+another order, like in ``send('Hello again', 'World', bcc='God', cc='Cthulhu')``.
+Those two possibilities are better avoided without any strong reason to not
+follow the syntax that is the closest to the function definition: ``send('Hello',
+'World', cc='Cthulhu', bcc='God')``.
+
+As a side note, following `YAGNI `_
+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
+new optional argument and its logic when needed.
+
+The **arbitrary argument list** is the third way to pass arguments to a
+function. If the function intention is better expressed by a signature with an
+extensible number of positional arguments, it can be defined with the ``*args``
+constructs. In the function body, ``args`` will be a tuple of all the
+remaining positional arguments. For example, ``send(message, *args)`` can be
+called with each recipient as an argument: ``send('Hello', 'God', 'Mom',
+'Cthulhu')``, and in the function body ``args`` will be equal to ``('God',
+'Mom', 'Cthulhu')``.
+
+However, this construct has some drawbacks and should be used with caution. If a
+function receives a list of arguments of the same nature, it is often more
+clear to define it as a function of one argument, that argument being a list or
+any sequence. Here, if ``send`` has multiple recipients, it is better to define
+it explicitly: ``send(message, recipients)`` and call it with ``send('Hello',
+['God', 'Mom', 'Cthulhu'])``. This way, the user of the function can manipulate
+the recipient list as a list beforehand, and it opens the possibility to pass
+any sequence, including iterators, that cannot be unpacked as other sequences.
+
+The **arbitrary keyword argument dictionary** is the last way to pass arguments
+to functions. If the function requires an undetermined series of named
+arguments, it is possible to used the ``**kwargs`` construct. In the function
+body, ``kwargs`` will be a dictionary of all the passed named arguments that
+have not been caught be other keyword argument in the function signature.
+
+The same caution as in the case of *arbitrary argument list* is necessary, for
+similar reasons: these powerful techniques are to be used when there is a
+proven necessity to use them, and they should not be used if the simpler and
+clearer construct is sufficient to express the function's intention.
+
+It is up to the programmer writing the function to determine which arguments
+are positional arguments and which are optional keyword arguments, and to
+decide whether to use the advanced techniques of arbitrary argument passing. If
+the advice above is followed wisely, it is possible and enjoyable to write
+Python functions that are:
+
+* easy to read (the name and arguments need no explanations)
+
+* easy to change (adding a new keyword argument does not break other parts of the
+ code)
+
+Avoid the magical wand
+~~~~~~~~~~~~~~~~~~~~~~
+
+A powerful tool for hackers, Python comes with a very rich set of hooks and
+tools allowing to do almost any kind of tricky tricks. For instance, it is
+possible to change how objects are created and instantiated, it is possible to
+change how the Python interpreter imports modules, it is even possible (and
+recommended if needed) to embed C routines in Python.
+
+However, all these options have many drawbacks and it is always better to use
+the most straightforward way to achieve your goal. The main drawback is that
+readability suffers deeply from them. Many code analysis tools, such as pylint
+or pyflakes, will be unable to parse this "magic" code.
+
+We consider that a Python developer should know about these nearly infinite
+possibilities, because it grows the confidence that no hard-wall will be on the
+way. However, knowing how to use them and particularly when **not** to use
+them is the most important.
+
+Like a Kungfu master, a Pythonista knows how to kill with a single finger, and
+never to do it.
+
+We are all consenting adults
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+As seen above, Python allows many tricks, and some of them are potentially
+dangerous. A good example is that any client code can override an object's
+properties and methods: there is no "private" keyword in Python. This
+philosophy, very different from highly defensive languages like Java, which
+give a lot of mechanism to prevent any misuse, is expressed by the saying: "We
+are consenting adults".
+
+This doesn't mean that, for example, no properties are considered private, and
+that no proper encapsulation is possible in Python. But, instead of relying on
+concrete walls erected by the developers between their code and other's, the
+Python community prefers to rely on a set of convention indicating that these
+elements should not be accessed directly.
+
+The main convention for private properties and implementation details is to
+prefix all "internals" with an underscore. If the client code breaks this rule
+and access to these marked elements, any misbehavior or problems encountered if
+the code is modified is the responsibility of the client code.
+
+Using this convention generously is encouraged: any method or property that is
+not intended to be used by client code should be prefixed with an underscore.
+This will guarantee a better separation of duties and easier modifications of
+existing code, and it will always be possible to publicize a private property,
+while privatising a public property might be a much harder operation.
+
+Returning values
+~~~~~~~~~~~~~~~~
+
+When a function grows in complexity is not uncommon to use multiple return statements
+inside the function's body. However, in order to keep a clear intent and a sustainable
+readability level, it is preferable to avoid returning meaningful values from many
+output point in the body.
+
+There are two main cases for returning values in a function: The result of the function
+return when it has been processed normally, and the error cases that indicate a wrong
+input parameter or any other reason for the function to not be able to complete its
+computation or task.
+
+If you do not wish to raise exceptions for the second case, then returning a value, such
+as None or False, indicating that the function could not perform correctly might be needed. In this
+case, it is better to return as early as the incorrect context has been detected. It will
+help to flatten the structure of the function: all the code after the return-because-of-error
+statement can assume the condition is met to further compute the function's main result.
+Having multiple such return statement is often necessary.
+
+However, when a function has multiple main exit points for its normal course, it becomes
+difficult to debug the returned result, and it may be preferable to keep a single exit
+point. This will also help factoring out some code paths, and the multiple exit point
+is a probable indication that such a refactoring is needed.
+
+.. code-block:: python
+
+ def complex_function(a, b, c):
+ if not a:
+ return None # Raising an exception might be better
+ if not b:
+ return None # Raising an exception might be better
+ # Some complex code trying to compute x from a, b and c
+ # Resist temptation to return x if succeeded
+ if not x:
+ # Some Plan-B computation of x
+ return x # One single exit point for the returned value x will help
+ # when maintaining the code.
+
+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
+
+Nested unpacking works too:
+
+.. code-block:: python
+
+ a, (b, c) = 1, (2, 3)
+
+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('.')
+
+.. note::
+
+ Many Python style guides recommend the use of a single underscore "``_``"
+ for throwaway variables rather than the double underscore "``__``"
+ recommended here. The issue is that "``_``" is commonly used as an alias
+ for the :func:`~gettext.gettext` function, and is also used at the
+ interactive prompt to hold the value of the last operation. Using a
+ double underscore instead is just as clear and almost as convenient,
+ and eliminates the risk of accidentally interfering with either of
+ these other use cases.
+
+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)]
+
+
+A common idiom for creating strings is to use `join `_ on an empty string.::
+
+ letters = ['s', 'p', 'a', 'm']
+ word = ''.join(letters)
+
+This will set the value of the variable *word* to 'spam'. This idiom can be applied to lists and tuples.
+
+Sometimes we need to search through a collection of things. Let's look at two options: lists and dictionaries.
+
+Take the following code for example::
+
+ d = {'s': [], 'p': [], 'a': [], 'm': []}
+ l = ['s', 'p', 'a', 'm']
+
+ def lookup_dict(d):
+ return 's' in d
+
+ def lookup_list(l):
+ return 's' in l
+
+Even though both functions look identical, because *lookup_dict* is utilizing the fact that dictionaries in python are hashtables, the lookup performance between the two is very different.
+Python will have to go through each item in the list to find a matching case, which is time consuming. By analysing the hash of the dictionary finding keys in the dict can be done very quickly.
+For more information see this `StackOverflow `_ page.
+
+Zen of Python
+-------------
+
+Also known as PEP 20, the guiding principles for Python's design.
+
+::
+
+ >>> import this
+ The Zen of Python, by Tim Peters
+
+ Beautiful is better than ugly.
+ Explicit is better than implicit.
+ Simple is better than complex.
+ Complex is better than complicated.
+ Flat is better than nested.
+ Sparse is better than dense.
+ Readability counts.
+ Special cases aren't special enough to break the rules.
+ Although practicality beats purity.
+ Errors should never pass silently.
+ Unless explicitly silenced.
+ In the face of ambiguity, refuse the temptation to guess.
+ There should be one-- and preferably only one --obvious way to do it.
+ Although that way may not be obvious at first unless you're Dutch.
+ Now is better than never.
+ Although never is often better than *right* now.
+ If the implementation is hard to explain, it's a bad idea.
+ If the implementation is easy to explain, it may be a good idea.
+ Namespaces are one honking great idea -- let's do more of those!
+
+For some examples of good Python style, see `this Stack Overflow question
+`_ or `these
+slides from a Python user group
+`_.
+
+PEP 8
+-----
+
+PEP 8 is the de-facto code style guide for Python.
+
+ `PEP 8 `_
+
+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
+exists a command-line program, `pep8 `_,
+that can check your code for conformance. Install it by running the following
+command in your Terminal:
+
+::
+
+ $ pip install pep8
+
+
+Then run it on a file or series of files to get a report of any violations.
+
+::
+
+ $ pep8 optparse.py
+ optparse.py:69:11: E401 multiple imports on one line
+ optparse.py:77:1: E302 expected 2 blank lines, found 1
+ optparse.py:88:5: E301 expected 1 blank line, found 0
+ optparse.py:222:34: W602 deprecated form of raising exception
+ optparse.py:347:31: E211 whitespace before '('
+ optparse.py:357:17: E201 whitespace after '{'
+ optparse.py:472:29: E221 multiple spaces before operator
+ optparse.py:544:21: W601 .has_key() is deprecated, use 'in'
+
+Conventions
+----------------
+
+Here are some conventions you should follow to make your code easier to read.
+
+Check if variable equals a constant
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+You don't need to explicitly compare a value to True, or None, or 0 - you can
+just add it to the if statement. See `Truth Value Testing
+`_ for a
+list of what is considered false.
+
+**Bad**:
+
+.. code-block:: python
+
+ if attr == True:
+ print 'True!'
+
+ if attr == None:
+ print 'attr is None!'
+
+**Good**:
+
+.. code-block:: python
+
+ # Just check the value
+ if attr:
+ print 'attr is truthy!'
+
+ # or check for the opposite
+ if not attr:
+ print 'attr is falsey!'
+
+ # or, since None is considered false, explicity check for it
+ if attr is None:
+ print 'attr is None!'
+
+Access a Dictionary Element
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Don't use the ``has_key`` function. Instead use ``x in d`` syntax, or pass
+a default argument to ``get``.
+
+**Bad**:
+
+.. code-block:: python
+
+ d = {'hello': 'world'}
+ if d.has_key('hello'):
+ print d['hello'] # prints 'world'
+ else:
+ print 'default_value'
+
+**Good**:
+
+.. code-block:: python
+
+ d = {'hello': 'world'}
+
+ print d.get('hello', 'default_value') # prints 'world'
+ print d.get('thingy', 'default_value') # prints 'default_value'
+
+ # Or:
+ if 'hello' in d:
+ print d['hello']
+
+Short Ways to Manipulate Lists
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+`List comprehensions
+`_
+provide a powerful, concise way to work with lists. Also, the `map
+`_ and `filter
+`_ functions can perform
+operations on lists using a different concise syntax.
+
+**Bad**:
+
+.. code-block:: python
+
+ # Filter elements greater than 4
+ a = [3, 4, 5]
+ b = []
+ for i in a:
+ if i > 4:
+ b.append(i)
+
+**Good**:
+
+.. code-block:: python
+
+ b = [i for i in a if i > 4]
+ b = filter(lambda x: x > 4, a)
+
+**Bad**:
+
+.. code-block:: python
+
+ # Add three to all list members.
+ a = [3, 4, 5]
+ count = 0
+ for i in a:
+ a[count] = i + 3
+ count = count + 1
+
+**Good**:
+
+.. code-block:: python
+
+ a = [3, 4, 5]
+ a = [i + 3 for i in a]
+ # Or:
+ a = map(lambda i: i + 3, a)
+
+Use `enumerate `_ to
+keep a count of your place in the list.
+
+.. code-block:: python
+
+ for i, item in enumerate(a):
+ print i + ", " + item
+ # prints
+ # 0, 3
+ # 1, 4
+ # 2, 5
+
+The ``enumerate`` function has better readability than handling a counter
+manually. Moreover,
+it is better optimized for iterators.
+
+Read From a File
+~~~~~~~~~~~~~~~~
+
+Use the ``with open`` syntax to read from files. This will automatically close
+files for you.
+
+**Bad**:
+
+.. code-block:: python
+
+ f = open('file.txt')
+ a = f.read()
+ print a
+ f.close()
+
+**Good**:
+
+.. code-block:: python
+
+ with open('file.txt') as f:
+ for line in f:
+ print line
+
+The ``with`` statement is better because it will ensure you always close the
+file, even if an exception is raised.
+
+Line Continuations
+~~~~~~~~~~~~~~~~~~
+
+When a logical line of code is longer than the accepted limit, you need to
+split it over multiple physical lines. Python interpreter will join consecutive
+lines if the last character of the line is a backslash. This is helpful
+sometime but is preferably avoided, because of its fragility: a white space
+added to the end of the line, after the backslash, will break the code and may
+have unexpected results.
+
+A preferred solution is to use parenthesis around your elements. Left with an
+unclosed parenthesis on an end-of-line the Python interpreter will join the
+next line until the parenthesis is closed. The same behavior holds for curly
+and square braces.
+
+**Bad**:
+
+.. code-block:: python
+
+ my_very_big_string = """For a long time I used to go to bed early. Sometimes, \
+ when I had put out my candle, my eyes would close so quickly that I had not even \
+ time to say “I’m going to sleep.”"""
+
+ from some.deep.module.inside.a.module import a_nice_function, another_nice_function, \
+ yet_another_nice_function
+
+**Good**:
+
+.. code-block:: python
+
+ my_very_big_string = (
+ "For a long time I used to go to bed early. Sometimes, "
+ "when I had put out my candle, my eyes would close so quickly "
+ "that I had not even time to say “I’m going to sleep.”"
+ )
+
+ from some.deep.module.inside.a.module import (
+ a_nice_function, another_nice_function, yet_another_nice_function)
+
+However, more often than not having to split long logical line is a sign that
+you are trying to do too many things at the same time, which may hinder
+readability.
From d00182b5416d1369e11f74a23c2a8476d7cd6553 Mon Sep 17 00:00:00 2001
From: Lambda Adi
Date: Sun, 27 Jan 2013 15:04:09 +0530
Subject: [PATCH 0103/1232] Clarified point about variable names
"Avoid using variables for different things" is misleading at best. The
point must communicate that foolish reuse of _the same_ variable name,
for different types of data, is the hobgoblin of reckless minds :)
---
docs/writing/structure.rst | 950 ++++++++++++++++++-------------------
1 file changed, 475 insertions(+), 475 deletions(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index 21133d846..ad37bb74a 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -1,475 +1,475 @@
-Structuring Your Project
-========================
-
-By "structure" we mean the decisions you make concerning
-how your project best meets its objective. We need to consider how to
-best leverage Python's features to create clean, effective code.
-In practical terms, "structure" means making clean code whose logic and
-dependencies are clear as well as how the files and folders are organized
-in the filesystem.
-
-Which functions should go into which modules? How does data flow through
-the project? What features and functions can be grouped together and
-isolated? By answering questions like these you can begin to plan, in
-a broad sense, what your finished product will look like.
-
-In this section we take a closer look at Python's module and import
-systems as they are the central element to enforcing structure in your
-project. We then discuss various perspectives on how to build code which
-can be extended and tested reliably.
-
-
-Structure is Key
-----------------
-
-Thanks to the way imports and modules are handled in Python, it is
-relatively easy to structure a Python project. Easy, here, means
-that you do not have many constraints and that the module
-importing model is easy to grasp. Therefore, you are left with the
-pure architectural task of crafting the different parts of your
-project and their interactions.
-
-Easy structuring of a project means it is also easy
-to do it poorly. Some signs of a poorly structured project
-include:
-
-- Multiple and messy circular dependencies: if your classes
- Table and Chair in furn.py need to import Carpenter from workers.py
- to answer a question such as table.isdoneby(),
- and if conversely the class Carpenter needs to import Table and Chair,
- to answer the question carpenter.whatdo(), then you
- have a circular dependency. In this case you will have to resort to
- fragile hacks such as using import statements inside
- methods or functions.
-
-- Hidden coupling: each and every change in Table's implementation
- breaks 20 tests in unrelated test cases because it breaks Carpenter's code,
- which requires very careful surgery to adapt the change. This means
- you have too many assumptions about Table in Carpenter's code or the
- reverse.
-
-- Heavy usage of global state or context: instead of explicitly
- passing ``(height, width, type, wood)`` to each other, Table
- and Carpenter rely on global variables that can be modified
- and are modified on the fly by different agents. You need to
- scrutinize all access to these global variables to understand why
- a rectangular table became a square, and discover that remote
- template code is also modifying this context, messing with
- table dimensions.
-
-- Spaghetti code: multiple pages of nested if clauses and for loops
- with a lot of copy-pasted procedural code and no
- proper segmentation are known as spaghetti code. Python's
- meaningful indentation (one of its most controversial features) make
- it very hard to maintain this kind of code. So the good news is that
- you might not see too much of it.
-
-- Ravioli code is more likely in Python: it consists of hundreds of
- similar little pieces of logic, often classes or objects, without
- proper structure. If you never can remember if you have to use
- FurnitureTable, AssetTable or Table, or even TableNew for your
- task at hand, you might be swimming in ravioli code.
-
-
-Modules
--------
-
-Python modules are one of the main abstraction layers available and probably the
-most natural one. Abstraction layers allow separating code into parts holding
-related data and functionality.
-
-For example, a layer of a project can handle interfacing with user actions,
-while another would handle low-level manipulation of data. The most natural way
-to separate these two layers is to regroup all interfacing functionality
-in one file, and all low-level operations in another file. In this case,
-the interface file needs to import the low-level file. This is done with the
-`import` and `from ... import` statements.
-
-As soon as you use `import` statements you use modules. These can be either built-in
-modules such as `os` and `sys`, third-party modules you have installed in your
-environment, or your project's internal modules.
-
-To keep in line with the style guide, keep module names short, lowercase, and
-be sure to avoid using special symbols like the dot (.) or question mark (?).
-So a file name like `my.spam.py` is one you should try to avoid! Naming this way
-will interfere with the way python looks for modules.
-
-In this example python expects to find a "spam.py" file in a folder named "my"
-which is not the case. There is an
-`example `_ of how the
-dot notation should be used in the python docs.
-
-If you'd like you could name it as `my_spam.py` but even our friend the
-underscore should not be seen often in module names.
-
-Aside for some naming restrictions, nothing special is required for a Python file
-to be a module, but the import mechanism needs to be understood in order to use
-this concept properly and avoid some issues.
-
-Concretely, the `import modu` statement will look for the proper file, which is
-`modu.py` in the same directory as the caller if it exists. If it is not
-found, the Python interpreter will search for `modu.py` in the "path"
-recursively and raise an ImportError exception if it is not found.
-
-Once `modu.py` is found, the Python interpreter will execute the module in an
-isolated scope. Any top-level statement in `modu.py` will be executed,
-including other imports if any. Function and class definitions are stored in
-the module's dictionary.
-
-Then, the module's variables, functions, and classes will be available to the caller
-through the module's namespace, a central concept in programming that is
-particularly helpful and powerful in Python.
-
-In many languages, an `include file` directive is used by the preprocessor to
-take all code found in the file and 'copy' it into the caller's code. It is
-different in Python: the included code is isolated in a module namespace, which
-means that you generally don't have to worry that the included code could have
-unwanted effects, e.g. override an existing function with the same name.
-
-It is possible to simulate the more standard behavior by using a special syntax
-of the import statement: `from modu import *`. This is generally considered bad
-practice. **Using `import *` makes code harder to read and makes dependencies less
-compartmentalized**.
-
-Using `from modu import func` is a way to pinpoint the function you want to
-import and put it in the global namespace. While much less harmful than `import
-*` because it shows explicitly what is imported in the global namespace, its
-advantage over a simpler `import modu` is only that it will save some typing.
-
-**Very bad**
-
-.. code-block:: python
-
- [...]
- from modu import *
- [...]
- x = sqrt(4) # Is sqrt part of modu? A builtin? Defined above?
-
-**Better**
-
-.. code-block:: python
-
- from modu import sqrt
- [...]
- x = sqrt(4) # sqrt may be part of modu, if not redefined in between
-
-**Best**
-
-.. code-block:: python
-
- import modu
- [...]
- x = modu.sqrt(4) # sqrt is visibly part of modu's namespace
-
-As said in the section about style, readability is one of the main features of
-Python. Readability means to avoid useless boilerplate text and clutter,
-therefore some efforts are spent trying to achieve a certain level of brevity.
-But terseness and obscurity are the limits where brevity should stop. Being
-able to tell immediately where a class or function comes from, as in the
-`modu.func` idiom, greatly improves code readability and understandability in
-all but the simplest single file projects.
-
-
-Packages
---------
-
-Python provides a very straightforward packaging system, which is simply an
-extension of the module mechanism to a directory.
-
-Any directory with an __init__.py file is considered a Python package. The
-different modules in the package are imported in a similar manner as plain
-modules, but with a special behavior for the __init__.py file, which is used to
-gather all package-wide definitions.
-
-A file modu.py in the directory pack/ is imported with the statement `import
-pack.modu`. This statement will look for an __init__.py file in `pack`, execute
-all of its top-level statements. Then it will look for a file `pack/modu.py` and
-execute all of its top-level statements. After these operations, any variable,
-function, or class defined in modu.py is available in the pack.modu namespace.
-
-A commonly seen issue is to add too much code to __init__.py
-files. When the project complexity grows, there may be sub-packages and
-sub-sub-packages in a deep directory structure, and then, importing a single item
-from a sub-sub-package will require executing all __init__.py files met while
-traversing the tree.
-
-Leaving an __init__.py file empty is considered normal and even a good practice,
-if the package's modules and sub-packages do not need to share any code.
-
-Lastly, a convenient syntax is available for importing deeply nested packages:
-`import very.deep.module as mod`. This allows you to use `mod` in place of the verbose
-repetition of `very.deep.module`.
-
-Object-oriented programming
----------------------------
-
-Python is sometimes described as an object-oriented programming language. This
-can be somewhat misleading and needs to be clarified.
-
-In Python, everything is an object, and can be handled as such. This is what is
-meant when we say that, for example, functions are first-class objects.
-Functions, classes, strings, and even types are objects in Python: like any
-objects, they have a type, they can be passed as function arguments, they may
-have methods and properties. In this understanding, Python is an
-object-oriented language.
-
-However, unlike Java, Python does not impose object-oriented programming as the
-main programming paradigm. It is perfectly viable for a Python project to not
-be object-oriented, i.e. to use no or very few class definitions, class
-inheritance, or any other mechanisms that are specific to object-oriented
-programming.
-
-Moreover, as seen in the modules_ section, the way Python handles modules and
-namespaces gives the developer a natural way to ensure the
-encapsulation and separation of abstraction layers, both being the most common
-reasons to use object-orientation. Therefore, Python programmers have more
-latitude to not use object-orientation, when it is not required by the business
-model.
-
-There are some reasons to avoid unnecessary object-orientation. Defining
-custom classes is useful when we want to glue together some state and some
-functionality. The problem, as pointed out by the discussions about functional
-programming, comes from the "state" part of the equation.
-
-In some architectures, typically web applications, multiple instances of Python
-processes are spawned to respond to external requests that can
-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
-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
-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
-memory and mark it as read by a user. If another request requires the deletion
-of this item at the same, it may happen that the deletion actually occurs after
-the first process loaded the item, and then we have to mark as read a deleted
-object.
-
-This and other issues led to the idea that using stateless functions is a
-better programming paradigm.
-
-Another way to say the same thing is to suggest using functions and procedures
-with as few implicit contexts and side-effects as possible. A function's
-implicit context is made up of any of the global variables or items in the persistence layer
-that are accessed from within the function. Side-effects are the changes that a function makes
-to its implicit context. If a function saves or deletes data in a global variable or
-in the persistence layer, it is said to have a side-effect.
-
-Carefully isolating functions with context and side-effects from functions with
-logic (called pure functions) allow the following benefits:
-
-- Pure functions are deterministic: given a fixed input,
- the output will always be the same.
-
-- Pure functions are much easier to change or replace if they need to
- be refactored or optimized.
-
-- Pure functions are easier to test with unit-tests: There is less
- need for complex context setup and data cleaning afterwards.
-
-- Pure functions are easier to manipulate, decorate, and pass-around.
-
-In summary, pure functions, without any context or side-effects, are more
-efficient building blocks than classes and objects for some architectures.
-
-Obviously, object-orientation is useful and even necessary in many cases, for
-example when developing graphical desktop applications or games, where the
-things that are manipulated (windows, buttons, avatars, vehicles) have a
-relatively long life of their own in the computer's memory.
-
-
-Decorators
-----------
-
-The Python language provides a simple yet powerful syntax called 'decorators'.
-A decorator is a function or a class that wraps (or decorate) a function
-or a method. The 'decorated' function or method will replace the original
-'undecorated' function or method. Because functions are first-class objects
-in Python, it can be done 'manually', but using the @decorator syntax is
-clearer and thus preferred.
-
-.. code-block:: python
-
- def foo():
- # do something
-
- def decorator(func):
- # manipulate func
- return func
-
- foo = decorator(foo) # Manually decorate
-
- @decorator
- def bar():
- # Do something
- # bar() is decorated
-
-This mechanism is useful for separating concerns and avoiding
-external un-related logic 'polluting' the core logic of the function
-or method. A good example of a piece of functionality that is better handled
-with decoration is memoization or caching: you want to store the results of an
-expensive function in a table and use them directly instead of recomputing
-them when they have already been computed. This is clearly not part
-of the function logic.
-
-Dynamic typing
---------------
-
-Python is said to be dynamically typed, which means that variables
-do not have a fixed type. In fact, in Python, variables are very
-different from what they are in many other languages, specifically
-strongly-typed languages. Variables are not a segment of the computer's
-memory where some value is written, they are 'tags' or 'names' pointing
-to objects. It is therefore possible for the variable 'a' to be set to
-the value 1, then to the value 'a string', then to a function.
-
-The dynamic typing of Python is often considered to be a weakness, and indeed
-it can lead to complexities and hard-to-debug code. Something
-named 'a' can be set to many different things, and the developer or the
-maintainer needs to track this name in the code to make sure it has not
-been set to a completely unrelated object.
-
-Some guidelines help to avoid this issue:
-
-- Avoid using variables for different things.
-
-**Bad**
-
-.. code-block:: python
-
- a = 1
- a = 'a string'
- def a():
- pass # Do something
-
-**Good**
-
-.. code-block:: python
-
- count = 1
- msg = 'a string'
- def func():
- pass # Do something
-
-Using short functions or methods helps reduce the risk
-of using the same name for two unrelated things.
-
-It is better to use different names even for things that are related,
-when they have a different type:
-
-**Bad**
-
-.. code-block:: python
-
- items = 'a b c d' # This is a string...
- items = items.split(' ') # ...becoming a list
- items = set(items) # ...and then a set
-
-There is no efficiency gain when reusing names: the assignments
-will have to create new objects anyway. However, when the complexity
-grows and each assignment is separated by other lines of code, including
-'if' branches and loops, it becomes harder to ascertain what a given
-variable's type is.
-
-Some coding practices, like functional programming, recommend never reassigning a variable.
-In Java this is done with the `final` keyword. Python does not have a `final` keyword
-and it would be against its philosophy anyway. However, it may be a good
-discipline to avoid assigning to a variable more than once, and it helps
-in grasping the concept of mutable and immutable types.
-
-Mutable and immutable types
----------------------------
-
-Python has two kinds of built-in or user-defined types.
-
-Mutable types are those that allow in-place modification
-of the content. Typical mutables are lists and dictionaries:
-All lists have mutating methods, like append() or pop(), and
-can be modified in place. The same goes for dictionaries.
-
-Immutable types provide no method for changing their content.
-For instance, the variable x set to the integer 6 has no "increment" method. If you
-want to compute x + 1, you have to create another integer and give it
-a name.
-
-.. code-block:: python
-
- my_list = [1, 2, 3]
- my_list[0] = 4
- print my_list # [4, 2, 3] <- The same list as changed
-
- x = 6
- x = x + 1 # The new x is another object
-
-One consequence of this difference in behavior is that mutable
-types are not "stable", and therefore cannot be used as dictionary
-keys.
-
-Using properly mutable types for things that are mutable in nature
-and immutable types for things that are fixed in nature
-helps to clarify the intent of the code.
-
-For example, the immutable equivalent of a list is the tuple, created
-with ``(1, 2)``. This tuple is a pair that cannot be changed in-place,
-and can be used as a key for a dictionary.
-
-One peculiarity of Python that can surprise beginners is that
-strings are immutable. This means that when constructing a string from
-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
-full string is needed. One thing to notice, however, is that list
-comprehensions are better and faster than constructing a list in a loop
-with calls to append().
-
-**Bad**
-
-.. code-block:: python
-
- # create a concatenated string from 0 to 19 (e.g. "012..1819")
- nums = ""
- for n in range(20):
- nums += str(n) # slow and inefficient
- print nums
-
-**Good**
-
-.. code-block:: python
-
- # create a concatenated string from 0 to 19 (e.g. "012..1819")
- nums = []
- for n in range(20):
- nums.append(str(n))
- print "".join(nums) # much more efficient
-
-**Best**
-
-.. code-block:: python
-
- # create a concatenated string from 0 to 19 (e.g. "012..1819")
- print "".join([str(n) for n in range(20)])
-
-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
-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()
-should be your preferred method.
-
-.. code-block:: python
-
- foo = 'foo'
- bar = 'bar'
-
- foobar = foo + bar # This is good
- foo += 'ooo' # This is bad, instead you should do:
- foo = ''.join([foo, 'ooo'])
-
-Vendorizing Dependencies
-------------------------
-
-
-
-Runners
--------
-
-
-Further Reading
----------------
+Structuring Your Project
+========================
+
+By "structure" we mean the decisions you make concerning
+how your project best meets its objective. We need to consider how to
+best leverage Python's features to create clean, effective code.
+In practical terms, "structure" means making clean code whose logic and
+dependencies are clear as well as how the files and folders are organized
+in the filesystem.
+
+Which functions should go into which modules? How does data flow through
+the project? What features and functions can be grouped together and
+isolated? By answering questions like these you can begin to plan, in
+a broad sense, what your finished product will look like.
+
+In this section we take a closer look at Python's module and import
+systems as they are the central element to enforcing structure in your
+project. We then discuss various perspectives on how to build code which
+can be extended and tested reliably.
+
+
+Structure is Key
+----------------
+
+Thanks to the way imports and modules are handled in Python, it is
+relatively easy to structure a Python project. Easy, here, means
+that you do not have many constraints and that the module
+importing model is easy to grasp. Therefore, you are left with the
+pure architectural task of crafting the different parts of your
+project and their interactions.
+
+Easy structuring of a project means it is also easy
+to do it poorly. Some signs of a poorly structured project
+include:
+
+- Multiple and messy circular dependencies: if your classes
+ Table and Chair in furn.py need to import Carpenter from workers.py
+ to answer a question such as table.isdoneby(),
+ and if conversely the class Carpenter needs to import Table and Chair,
+ to answer the question carpenter.whatdo(), then you
+ have a circular dependency. In this case you will have to resort to
+ fragile hacks such as using import statements inside
+ methods or functions.
+
+- Hidden coupling: each and every change in Table's implementation
+ breaks 20 tests in unrelated test cases because it breaks Carpenter's code,
+ which requires very careful surgery to adapt the change. This means
+ you have too many assumptions about Table in Carpenter's code or the
+ reverse.
+
+- Heavy usage of global state or context: instead of explicitly
+ passing ``(height, width, type, wood)`` to each other, Table
+ and Carpenter rely on global variables that can be modified
+ and are modified on the fly by different agents. You need to
+ scrutinize all access to these global variables to understand why
+ a rectangular table became a square, and discover that remote
+ template code is also modifying this context, messing with
+ table dimensions.
+
+- Spaghetti code: multiple pages of nested if clauses and for loops
+ with a lot of copy-pasted procedural code and no
+ proper segmentation are known as spaghetti code. Python's
+ meaningful indentation (one of its most controversial features) make
+ it very hard to maintain this kind of code. So the good news is that
+ you might not see too much of it.
+
+- Ravioli code is more likely in Python: it consists of hundreds of
+ similar little pieces of logic, often classes or objects, without
+ proper structure. If you never can remember if you have to use
+ FurnitureTable, AssetTable or Table, or even TableNew for your
+ task at hand, you might be swimming in ravioli code.
+
+
+Modules
+-------
+
+Python modules are one of the main abstraction layers available and probably the
+most natural one. Abstraction layers allow separating code into parts holding
+related data and functionality.
+
+For example, a layer of a project can handle interfacing with user actions,
+while another would handle low-level manipulation of data. The most natural way
+to separate these two layers is to regroup all interfacing functionality
+in one file, and all low-level operations in another file. In this case,
+the interface file needs to import the low-level file. This is done with the
+`import` and `from ... import` statements.
+
+As soon as you use `import` statements you use modules. These can be either built-in
+modules such as `os` and `sys`, third-party modules you have installed in your
+environment, or your project's internal modules.
+
+To keep in line with the style guide, keep module names short, lowercase, and
+be sure to avoid using special symbols like the dot (.) or question mark (?).
+So a file name like `my.spam.py` is one you should try to avoid! Naming this way
+will interfere with the way python looks for modules.
+
+In this example python expects to find a "spam.py" file in a folder named "my"
+which is not the case. There is an
+`example `_ of how the
+dot notation should be used in the python docs.
+
+If you'd like you could name it as `my_spam.py` but even our friend the
+underscore should not be seen often in module names.
+
+Aside for some naming restrictions, nothing special is required for a Python file
+to be a module, but the import mechanism needs to be understood in order to use
+this concept properly and avoid some issues.
+
+Concretely, the `import modu` statement will look for the proper file, which is
+`modu.py` in the same directory as the caller if it exists. If it is not
+found, the Python interpreter will search for `modu.py` in the "path"
+recursively and raise an ImportError exception if it is not found.
+
+Once `modu.py` is found, the Python interpreter will execute the module in an
+isolated scope. Any top-level statement in `modu.py` will be executed,
+including other imports if any. Function and class definitions are stored in
+the module's dictionary.
+
+Then, the module's variables, functions, and classes will be available to the caller
+through the module's namespace, a central concept in programming that is
+particularly helpful and powerful in Python.
+
+In many languages, an `include file` directive is used by the preprocessor to
+take all code found in the file and 'copy' it into the caller's code. It is
+different in Python: the included code is isolated in a module namespace, which
+means that you generally don't have to worry that the included code could have
+unwanted effects, e.g. override an existing function with the same name.
+
+It is possible to simulate the more standard behavior by using a special syntax
+of the import statement: `from modu import *`. This is generally considered bad
+practice. **Using `import *` makes code harder to read and makes dependencies less
+compartmentalized**.
+
+Using `from modu import func` is a way to pinpoint the function you want to
+import and put it in the global namespace. While much less harmful than `import
+*` because it shows explicitly what is imported in the global namespace, its
+advantage over a simpler `import modu` is only that it will save some typing.
+
+**Very bad**
+
+.. code-block:: python
+
+ [...]
+ from modu import *
+ [...]
+ x = sqrt(4) # Is sqrt part of modu? A builtin? Defined above?
+
+**Better**
+
+.. code-block:: python
+
+ from modu import sqrt
+ [...]
+ x = sqrt(4) # sqrt may be part of modu, if not redefined in between
+
+**Best**
+
+.. code-block:: python
+
+ import modu
+ [...]
+ x = modu.sqrt(4) # sqrt is visibly part of modu's namespace
+
+As said in the section about style, readability is one of the main features of
+Python. Readability means to avoid useless boilerplate text and clutter,
+therefore some efforts are spent trying to achieve a certain level of brevity.
+But terseness and obscurity are the limits where brevity should stop. Being
+able to tell immediately where a class or function comes from, as in the
+`modu.func` idiom, greatly improves code readability and understandability in
+all but the simplest single file projects.
+
+
+Packages
+--------
+
+Python provides a very straightforward packaging system, which is simply an
+extension of the module mechanism to a directory.
+
+Any directory with an __init__.py file is considered a Python package. The
+different modules in the package are imported in a similar manner as plain
+modules, but with a special behavior for the __init__.py file, which is used to
+gather all package-wide definitions.
+
+A file modu.py in the directory pack/ is imported with the statement `import
+pack.modu`. This statement will look for an __init__.py file in `pack`, execute
+all of its top-level statements. Then it will look for a file `pack/modu.py` and
+execute all of its top-level statements. After these operations, any variable,
+function, or class defined in modu.py is available in the pack.modu namespace.
+
+A commonly seen issue is to add too much code to __init__.py
+files. When the project complexity grows, there may be sub-packages and
+sub-sub-packages in a deep directory structure, and then, importing a single item
+from a sub-sub-package will require executing all __init__.py files met while
+traversing the tree.
+
+Leaving an __init__.py file empty is considered normal and even a good practice,
+if the package's modules and sub-packages do not need to share any code.
+
+Lastly, a convenient syntax is available for importing deeply nested packages:
+`import very.deep.module as mod`. This allows you to use `mod` in place of the verbose
+repetition of `very.deep.module`.
+
+Object-oriented programming
+---------------------------
+
+Python is sometimes described as an object-oriented programming language. This
+can be somewhat misleading and needs to be clarified.
+
+In Python, everything is an object, and can be handled as such. This is what is
+meant when we say that, for example, functions are first-class objects.
+Functions, classes, strings, and even types are objects in Python: like any
+objects, they have a type, they can be passed as function arguments, they may
+have methods and properties. In this understanding, Python is an
+object-oriented language.
+
+However, unlike Java, Python does not impose object-oriented programming as the
+main programming paradigm. It is perfectly viable for a Python project to not
+be object-oriented, i.e. to use no or very few class definitions, class
+inheritance, or any other mechanisms that are specific to object-oriented
+programming.
+
+Moreover, as seen in the modules_ section, the way Python handles modules and
+namespaces gives the developer a natural way to ensure the
+encapsulation and separation of abstraction layers, both being the most common
+reasons to use object-orientation. Therefore, Python programmers have more
+latitude to not use object-orientation, when it is not required by the business
+model.
+
+There are some reasons to avoid unnecessary object-orientation. Defining
+custom classes is useful when we want to glue together some state and some
+functionality. The problem, as pointed out by the discussions about functional
+programming, comes from the "state" part of the equation.
+
+In some architectures, typically web applications, multiple instances of Python
+processes are spawned to respond to external requests that can
+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
+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
+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
+memory and mark it as read by a user. If another request requires the deletion
+of this item at the same, it may happen that the deletion actually occurs after
+the first process loaded the item, and then we have to mark as read a deleted
+object.
+
+This and other issues led to the idea that using stateless functions is a
+better programming paradigm.
+
+Another way to say the same thing is to suggest using functions and procedures
+with as few implicit contexts and side-effects as possible. A function's
+implicit context is made up of any of the global variables or items in the persistence layer
+that are accessed from within the function. Side-effects are the changes that a function makes
+to its implicit context. If a function saves or deletes data in a global variable or
+in the persistence layer, it is said to have a side-effect.
+
+Carefully isolating functions with context and side-effects from functions with
+logic (called pure functions) allow the following benefits:
+
+- Pure functions are deterministic: given a fixed input,
+ the output will always be the same.
+
+- Pure functions are much easier to change or replace if they need to
+ be refactored or optimized.
+
+- Pure functions are easier to test with unit-tests: There is less
+ need for complex context setup and data cleaning afterwards.
+
+- Pure functions are easier to manipulate, decorate, and pass-around.
+
+In summary, pure functions, without any context or side-effects, are more
+efficient building blocks than classes and objects for some architectures.
+
+Obviously, object-orientation is useful and even necessary in many cases, for
+example when developing graphical desktop applications or games, where the
+things that are manipulated (windows, buttons, avatars, vehicles) have a
+relatively long life of their own in the computer's memory.
+
+
+Decorators
+----------
+
+The Python language provides a simple yet powerful syntax called 'decorators'.
+A decorator is a function or a class that wraps (or decorate) a function
+or a method. The 'decorated' function or method will replace the original
+'undecorated' function or method. Because functions are first-class objects
+in Python, it can be done 'manually', but using the @decorator syntax is
+clearer and thus preferred.
+
+.. code-block:: python
+
+ def foo():
+ # do something
+
+ def decorator(func):
+ # manipulate func
+ return func
+
+ foo = decorator(foo) # Manually decorate
+
+ @decorator
+ def bar():
+ # Do something
+ # bar() is decorated
+
+This mechanism is useful for separating concerns and avoiding
+external un-related logic 'polluting' the core logic of the function
+or method. A good example of a piece of functionality that is better handled
+with decoration is memoization or caching: you want to store the results of an
+expensive function in a table and use them directly instead of recomputing
+them when they have already been computed. This is clearly not part
+of the function logic.
+
+Dynamic typing
+--------------
+
+Python is said to be dynamically typed, which means that variables
+do not have a fixed type. In fact, in Python, variables are very
+different from what they are in many other languages, specifically
+strongly-typed languages. Variables are not a segment of the computer's
+memory where some value is written, they are 'tags' or 'names' pointing
+to objects. It is therefore possible for the variable 'a' to be set to
+the value 1, then to the value 'a string', then to a function.
+
+The dynamic typing of Python is often considered to be a weakness, and indeed
+it can lead to complexities and hard-to-debug code. Something
+named 'a' can be set to many different things, and the developer or the
+maintainer needs to track this name in the code to make sure it has not
+been set to a completely unrelated object.
+
+Some guidelines help to avoid this issue:
+
+- Avoid using the same variable name for different things.
+
+**Bad**
+
+.. code-block:: python
+
+ a = 1
+ a = 'a string'
+ def a():
+ pass # Do something
+
+**Good**
+
+.. code-block:: python
+
+ count = 1
+ msg = 'a string'
+ def func():
+ pass # Do something
+
+Using short functions or methods helps reduce the risk
+of using the same name for two unrelated things.
+
+It is better to use different names even for things that are related,
+when they have a different type:
+
+**Bad**
+
+.. code-block:: python
+
+ items = 'a b c d' # This is a string...
+ items = items.split(' ') # ...becoming a list
+ items = set(items) # ...and then a set
+
+There is no efficiency gain when reusing names: the assignments
+will have to create new objects anyway. However, when the complexity
+grows and each assignment is separated by other lines of code, including
+'if' branches and loops, it becomes harder to ascertain what a given
+variable's type is.
+
+Some coding practices, like functional programming, recommend never reassigning a variable.
+In Java this is done with the `final` keyword. Python does not have a `final` keyword
+and it would be against its philosophy anyway. However, it may be a good
+discipline to avoid assigning to a variable more than once, and it helps
+in grasping the concept of mutable and immutable types.
+
+Mutable and immutable types
+---------------------------
+
+Python has two kinds of built-in or user-defined types.
+
+Mutable types are those that allow in-place modification
+of the content. Typical mutables are lists and dictionaries:
+All lists have mutating methods, like append() or pop(), and
+can be modified in place. The same goes for dictionaries.
+
+Immutable types provide no method for changing their content.
+For instance, the variable x set to the integer 6 has no "increment" method. If you
+want to compute x + 1, you have to create another integer and give it
+a name.
+
+.. code-block:: python
+
+ my_list = [1, 2, 3]
+ my_list[0] = 4
+ print my_list # [4, 2, 3] <- The same list as changed
+
+ x = 6
+ x = x + 1 # The new x is another object
+
+One consequence of this difference in behavior is that mutable
+types are not "stable", and therefore cannot be used as dictionary
+keys.
+
+Using properly mutable types for things that are mutable in nature
+and immutable types for things that are fixed in nature
+helps to clarify the intent of the code.
+
+For example, the immutable equivalent of a list is the tuple, created
+with ``(1, 2)``. This tuple is a pair that cannot be changed in-place,
+and can be used as a key for a dictionary.
+
+One peculiarity of Python that can surprise beginners is that
+strings are immutable. This means that when constructing a string from
+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
+full string is needed. One thing to notice, however, is that list
+comprehensions are better and faster than constructing a list in a loop
+with calls to append().
+
+**Bad**
+
+.. code-block:: python
+
+ # create a concatenated string from 0 to 19 (e.g. "012..1819")
+ nums = ""
+ for n in range(20):
+ nums += str(n) # slow and inefficient
+ print nums
+
+**Good**
+
+.. code-block:: python
+
+ # create a concatenated string from 0 to 19 (e.g. "012..1819")
+ nums = []
+ for n in range(20):
+ nums.append(str(n))
+ print "".join(nums) # much more efficient
+
+**Best**
+
+.. code-block:: python
+
+ # create a concatenated string from 0 to 19 (e.g. "012..1819")
+ print "".join([str(n) for n in range(20)])
+
+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
+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()
+should be your preferred method.
+
+.. code-block:: python
+
+ foo = 'foo'
+ bar = 'bar'
+
+ foobar = foo + bar # This is good
+ foo += 'ooo' # This is bad, instead you should do:
+ foo = ''.join([foo, 'ooo'])
+
+Vendorizing Dependencies
+------------------------
+
+
+
+Runners
+-------
+
+
+Further Reading
+---------------
From 0e989d75f39059878001c13bdb027af454d3cbd4 Mon Sep 17 00:00:00 2001
From: lambdadi
Date: Wed, 30 Jan 2013 18:23:08 +0530
Subject: [PATCH 0104/1232] Suggest improved introduction to Style/#Idioms
My reading, though limited, suggests that the general notion of Idioms
is used often, but rarely explained. It feels very alien to beginners. A
term like "Idiomatic Python" can cause mental stack overflow. It did to
me :) So I humbly submit, in this case, explicit is better than
implicit. I debated whether to place it at the top of the document,
where idioms are first mentioned, but placed it here instead, as this
section explicitly references the topic of idioms.
---
docs/writing/style.rst | 11 ++++++++++-
1 file changed, 10 insertions(+), 1 deletion(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index 919d3a147..41fac9b37 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -251,7 +251,16 @@ is a probable indication that such a refactoring is needed.
Idioms
------
-Idiomatic Python code is often referred to as being *Pythonic*.
+A programming Idiom, put simply, is _a way_ to write code. The notion of programming Idioms
+is discussed amply at `c2 ` and at `Stack Overflow `.
+
+Idiomatic Python code is often referred to as being *Pythonic*.
+
+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,
+good idioms must be consciously acquired.
+
+Some common Python idioms follow:
.. _unpacking-ref:
From a6f9cc35082ed35cdc5b717f2440a7f2c310b28c Mon Sep 17 00:00:00 2001
From: Michael Komitee
Date: Sun, 3 Feb 2013 21:47:03 -0500
Subject: [PATCH 0105/1232] Removing inaccurate statement
ctrl-v in vim activates visual block mode. visual block mode can be used to
insert a comment character, but is not itself a comment toggle.
---
docs/writing/documentation.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/documentation.rst b/docs/writing/documentation.rst
index d61da5166..7bc528768 100644
--- a/docs/writing/documentation.rst
+++ b/docs/writing/documentation.rst
@@ -116,7 +116,7 @@ practice, because line-oriented command-line tools such as grep will
not be aware that the commented code is inactive. It is better to add
hashes at the proper indentation level for every commented line. Your
editor probably has the ability to do this easily, and it is worth
-learning the comment/uncomment toggle. (*e.g.* ctrl-v on Vim)
+learning the comment/uncomment toggle.
Docstrings and Magic
~~~~~~~~~~~~~~~~~~~~
From 6871ce9dd085db443fd41cb3b3fcaf2c6e9cf1af Mon Sep 17 00:00:00 2001
From: Mahdi Yusuf
Date: Sun, 24 Feb 2013 03:33:52 -0500
Subject: [PATCH 0106/1232] adding pycoder's weekly to resources
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Didn't know this was a section here.
---
docs/intro/news.rst | 58 ++++++++++++++++++++++++++-------------------
1 file changed, 33 insertions(+), 25 deletions(-)
diff --git a/docs/intro/news.rst b/docs/intro/news.rst
index b24fa930f..0c8f74712 100644
--- a/docs/intro/news.rst
+++ b/docs/intro/news.rst
@@ -1,25 +1,33 @@
-News
-====
-
-Planet Python
-~~~~~~~~~~~~~
-
-This is an aggregate of Python news from a growing number of developers.
-
- `Planet Python `_
-
-/r/python
-~~~~~~~~~
-
-/r/python is the Reddit Python community where users contribute and vote on
-Python-related news.
-
- `/r/python `_
-
-Python Weekly
-~~~~~~~~~~~~~
-
-Python Weekly is a free weekly newsletter featuring curated news, articles,
-new releases, jobs, etc. related to Python.
-
- `Python Weekly `_
+News
+====
+
+Planet Python
+~~~~~~~~~~~~~
+
+This is an aggregate of Python news from a growing number of developers.
+
+ `Planet Python `_
+
+/r/python
+~~~~~~~~~
+
+/r/python is the Reddit Python community where users contribute and vote on
+Python-related news.
+
+ `/r/python `_
+
+Pycoder's Weekly
+~~~~~~~~~~~~~
+
+Pycoder's Weekly is a free weekly python newsletter for Python developers
+by Python developers (Project, Articles, News, and Jobs).
+
+ `Pycoder's Weekly `_
+
+Python Weekly
+~~~~~~~~~~~~~
+
+Python Weekly is a free weekly newsletter featuring curated news, articles,
+new releases, jobs, etc. related to Python.
+
+ `Python Weekly `_
From 3919c7d81594c4758896d3215b66d50850d4616f Mon Sep 17 00:00:00 2001
From: Rhys Elsmore
Date: Sun, 24 Feb 2013 21:03:56 +1100
Subject: [PATCH 0107/1232] Fixed Spelling Issue
---
docs/scenarios/speed.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/scenarios/speed.rst b/docs/scenarios/speed.rst
index e20c563ba..87a1f66f6 100644
--- a/docs/scenarios/speed.rst
+++ b/docs/scenarios/speed.rst
@@ -61,7 +61,7 @@ The GIL
`Special care`_ must be taken when writing C extensions to make sure you r
egister your threads with the interpreter.
-C Extentions
+C Extensions
::::::::::::
From 528a915e08930d1f53a9d414d232b94464d53c17 Mon Sep 17 00:00:00 2001
From: barisumog
Date: Fri, 1 Mar 2013 10:55:48 +0200
Subject: [PATCH 0108/1232] minor typos in style.rst
---
docs/writing/style.rst | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index 919d3a147..614817648 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -109,7 +109,7 @@ passed another value.
Calling a function with keyword arguments can be done in multiple ways in Python,
for example it is possible to follow the order of arguments in the definition without
explicitly naming the arguments, like in ``send('Hello', 'World', 'Cthulhu', 'God')``,
-sending a blank carbon copy to God. It would also be possible to name arguments in
+sending a blind carbon copy to God. It would also be possible to name arguments in
another order, like in ``send('Hello again', 'World', bcc='God', cc='Cthulhu')``.
Those two possibilities are better avoided without any strong reason to not
follow the syntax that is the closest to the function definition: ``send('Hello',
@@ -140,9 +140,9 @@ any sequence, including iterators, that cannot be unpacked as other sequences.
The **arbitrary keyword argument dictionary** is the last way to pass arguments
to functions. If the function requires an undetermined series of named
-arguments, it is possible to used the ``**kwargs`` construct. In the function
+arguments, it is possible to use the ``**kwargs`` construct. In the function
body, ``kwargs`` will be a dictionary of all the passed named arguments that
-have not been caught be other keyword argument in the function signature.
+have not been caught by other keyword arguments in the function signature.
The same caution as in the case of *arbitrary argument list* is necessary, for
similar reasons: these powerful techniques are to be used when there is a
@@ -576,7 +576,7 @@ Line Continuations
When a logical line of code is longer than the accepted limit, you need to
split it over multiple physical lines. Python interpreter will join consecutive
lines if the last character of the line is a backslash. This is helpful
-sometime but is preferably avoided, because of its fragility: a white space
+sometimes but is preferably avoided, because of its fragility: a white space
added to the end of the line, after the backslash, will break the code and may
have unexpected results.
From 9f5bf3078fad51fa7a20a10e281f15c989415442 Mon Sep 17 00:00:00 2001
From: barisumog
Date: Fri, 1 Mar 2013 10:59:01 +0200
Subject: [PATCH 0109/1232] minor typo in reading.rst
---
docs/writing/reading.rst | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/docs/writing/reading.rst b/docs/writing/reading.rst
index 4ab1ddba1..8d1e816d0 100644
--- a/docs/writing/reading.rst
+++ b/docs/writing/reading.rst
@@ -9,7 +9,7 @@ One of the secrets of becoming a great Python programmer is to read,
understand, and comprehend excellent code.
Excellent code typically follows the guidelines outlined in :ref:`code_style`,
-and does its best to express a clear and consise intent to the reader.
+and does its best to express a clear and concise intent to the reader.
Included below is a list of recommended Python projects for reading. Each of
these projects are paragons of excellent Python code.
@@ -41,4 +41,4 @@ these projects are paragons of excellent Python code.
.. todo:: Include code examples of exemplary code from each of the projects listed. Explain why it is excellent code. Use complex examples.
-.. todo:: Explain techniques to rapidly identify data structures, algorithms and determine what the code is doing.
\ No newline at end of file
+.. todo:: Explain techniques to rapidly identify data structures, algorithms and determine what the code is doing.
From df402a1c8ee9cb977bb9bf9de0d9a1949b3b90fc Mon Sep 17 00:00:00 2001
From: barisumog
Date: Fri, 1 Mar 2013 11:04:24 +0200
Subject: [PATCH 0110/1232] minor typo in documentation.rst
---
docs/writing/documentation.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/documentation.rst b/docs/writing/documentation.rst
index d61da5166..88790849d 100644
--- a/docs/writing/documentation.rst
+++ b/docs/writing/documentation.rst
@@ -37,7 +37,7 @@ Project Publication
Depending on the project, your documentation might include some or all
of the following components:
-- A *introduction* should show a very short overview of what can be
+- An *introduction* should show a very short overview of what can be
done with the product, using one or two extremely simplified use
cases. This is the thirty-second pitch for your project.
From f7c306e20663b6cda266688ee69aa5a1bc53ddb3 Mon Sep 17 00:00:00 2001
From: barisumog
Date: Fri, 1 Mar 2013 11:13:33 +0200
Subject: [PATCH 0111/1232] minor typos
---
docs/writing/tests.rst | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/docs/writing/tests.rst b/docs/writing/tests.rst
index d70d613d9..70c08f577 100644
--- a/docs/writing/tests.rst
+++ b/docs/writing/tests.rst
@@ -20,7 +20,7 @@ Some general rules of testing:
- 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
- be run as often as desirable. In some cases, test can't be fast because they
+ be run as often as desirable. In some cases, tests can't be fast because they
need a complex data structure to work on, and this data structure must be
loaded every time the test runs. Keep these heavier tests in a separate test
suite that is run by some scheduled task, and run all other tests as often
@@ -34,10 +34,10 @@ Some general rules of testing:
after. This will give you more confidence that you did not break anything in
the rest of the code.
-- It is a good idea to implement a hook that runs all test before pushing code
+- It is a good idea to implement a hook that runs all tests before pushing code
to a shared repository.
-- If you are in the middle of a development and have to interrupt your work, it
+- If you are in the middle of a development session and have to interrupt your work, it
is a good idea to write a broken unit test about what you want to develop next.
When coming back to work, you will have a pointer to where you were and get
faster on tracks.
From a0761200eb3c3521da2a9561385e5ee62926ee6c Mon Sep 17 00:00:00 2001
From: barisumog
Date: Fri, 1 Mar 2013 11:15:55 +0200
Subject: [PATCH 0112/1232] minor typo
---
docs/writing/gotchas.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/gotchas.rst b/docs/writing/gotchas.rst
index 51b810565..1fa23e563 100644
--- a/docs/writing/gotchas.rst
+++ b/docs/writing/gotchas.rst
@@ -2,7 +2,7 @@ Common Gotchas
==============
For the most part, Python aims to be a clean and consistent language that
-avoid surprises, but there are a few cases where newcomers to the language
+avoids surprises, but there are a few cases where newcomers to the language
often get tripped up.
Some of these are intentional but potentially surprising. Some could arguably
From 6a5341cfce6d8835d965b13e518605e9c1356b42 Mon Sep 17 00:00:00 2001
From: gurpinars
Date: Mon, 4 Mar 2013 22:10:22 +0200
Subject: [PATCH 0113/1232] added further reading in structure.rst
---
docs/writing/structure.rst | 3 +++
1 file changed, 3 insertions(+)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index ad37bb74a..e2359cd66 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -473,3 +473,6 @@ Runners
Further Reading
---------------
+
+http://docs.python.org/2/library/
+http://www.diveintopython.net/toc/index.html
From 3ac59eb08c76e06e8a36c12269da107bf5cb204a Mon Sep 17 00:00:00 2001
From: gurpinars
Date: Mon, 4 Mar 2013 22:17:09 +0200
Subject: [PATCH 0114/1232] modified structure.rst
---
docs/writing/structure.rst | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index e2359cd66..456fd43af 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -474,5 +474,5 @@ Runners
Further Reading
---------------
-http://docs.python.org/2/library/
-http://www.diveintopython.net/toc/index.html
+- http://docs.python.org/2/library/
+- http://www.diveintopython.net/toc/index.html
From 87f65a4a2ccbb13a48c713fbcbc690ec91bb0e91 Mon Sep 17 00:00:00 2001
From: gurpinars
Date: Tue, 5 Mar 2013 01:21:19 +0200
Subject: [PATCH 0115/1232] added an url about scientific python in resource
---
docs/scenarios/scientific.rst | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/docs/scenarios/scientific.rst b/docs/scenarios/scientific.rst
index 758f0a1d7..46e1ba8d4 100644
--- a/docs/scenarios/scientific.rst
+++ b/docs/scenarios/scientific.rst
@@ -68,3 +68,7 @@ scientific computing packages are notoriously difficult to build and install.
compiled a list of Windows binaries for many useful Python packages. The list
of packages has grown from a mainly scientific python resource to a more
general list. It might be a good idea to check it out if you're on Windows.
+
+For a quick introduction to scientific python:
+
+`Scientific Python Lectures < http://scipy-lectures.github.com/>`_
From 564b449227534b2595cc7396f5cb0e291969b46e Mon Sep 17 00:00:00 2001
From: gurpinars
Date: Tue, 5 Mar 2013 01:24:15 +0200
Subject: [PATCH 0116/1232] fixed an typo
---
docs/scenarios/scientific.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/scenarios/scientific.rst b/docs/scenarios/scientific.rst
index 46e1ba8d4..5dadae7ce 100644
--- a/docs/scenarios/scientific.rst
+++ b/docs/scenarios/scientific.rst
@@ -71,4 +71,4 @@ general list. It might be a good idea to check it out if you're on Windows.
For a quick introduction to scientific python:
-`Scientific Python Lectures < http://scipy-lectures.github.com/>`_
+http://scipy-lectures.github.com
From 7915805501203cf59e5c73bebc5a43bed11d631a Mon Sep 17 00:00:00 2001
From: Valentin Haenel
Date: Thu, 21 Feb 2013 21:45:58 +0100
Subject: [PATCH 0117/1232] fix trailing whitespace
---
docs/scenarios/scientific.rst | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/docs/scenarios/scientific.rst b/docs/scenarios/scientific.rst
index 5dadae7ce..9ba928ab3 100644
--- a/docs/scenarios/scientific.rst
+++ b/docs/scenarios/scientific.rst
@@ -46,8 +46,8 @@ Installing NumPy and SciPy can be a daunting task. Which is why the
`Enthought Python distribution `_ was created. With
Enthought, scientific python has never been easier (one click to install about
100 scientific python packages). The Enthought Python Distribution comes in two
-variants: a free version `EPD Free `_
-and a paid version with various `pricing options.
+variants: a free version `EPD Free `_
+and a paid version with various `pricing options.
`_
Matplotlib
From 70c7f81441dfa306a832ce7afd41df0480bc549b Mon Sep 17 00:00:00 2001
From: Valentin Haenel
Date: Thu, 21 Feb 2013 21:52:02 +0100
Subject: [PATCH 0118/1232] add matplotlib to sentence about packages
In general, when people speak about scientific Python, the mention the trinity
of Numpy, Scipy and Matplotlib.
---
docs/scenarios/scientific.rst | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/docs/scenarios/scientific.rst b/docs/scenarios/scientific.rst
index 9ba928ab3..21bca2dfc 100644
--- a/docs/scenarios/scientific.rst
+++ b/docs/scenarios/scientific.rst
@@ -11,8 +11,8 @@ and it performs really well.
Due to its high performance nature, scientific computing in python often refers
to external libraries, typically written in faster languages (like C, or FORTRAN
-for matrix operations). The main libraries used are `NumPy`_ and
-`SciPy`_.
+for matrix operations). The main libraries used are `NumPy`_,
+`SciPy`_ and `Matplotlib`_.
Libraries
:::::::::
From 9ecebf5801d3289921f04522c9b4f955faa9682e Mon Sep 17 00:00:00 2001
From: Valentin Haenel
Date: Thu, 21 Feb 2013 21:53:39 +0100
Subject: [PATCH 0119/1232] move the Matplotlib section up
If the introduction mentions Numpy, Scipy and then Matplotlib -- they should
appear in that order in the 'Libraries' section.
---
docs/scenarios/scientific.rst | 17 +++++++++--------
1 file changed, 9 insertions(+), 8 deletions(-)
diff --git a/docs/scenarios/scientific.rst b/docs/scenarios/scientific.rst
index 21bca2dfc..e6c0602d7 100644
--- a/docs/scenarios/scientific.rst
+++ b/docs/scenarios/scientific.rst
@@ -39,6 +39,15 @@ modules for various commonly used tasks in scientific programing like linear
algebra, integration (calculus), ordinary differential equation solvers and
signal processing.
+Matplotlib
+----------
+
+`matplotlib `_ is a flexible plotting
+library for creating interactive 2D and 3D plots that can also be saved as
+manuscript-quality figures. The API in many ways reflects that of `MATLAB `_,
+easing transition of MATLAB users to Python. Many examples, along with the
+source code to re-create them, can be browsed at the `matplotlib gallery `_.
+
Enthought
---------
@@ -50,14 +59,6 @@ variants: a free version `EPD Free `
and a paid version with various `pricing options.
`_
-Matplotlib
-----------
-
-`matplotlib `_ is a flexible plotting
-library for creating interactive 2D and 3D plots that can also be saved as
-manuscript-quality figures. The API in many ways reflects that of `MATLAB `_,
-easing transition of MATLAB users to Python. Many examples, along with the
-source code to re-create them, can be browsed at the `matplotlib gallery `_.
Resources
:::::::::
From 39e0b381c1e5e3aea8dc5073c7e82a5bbfe2719d Mon Sep 17 00:00:00 2001
From: Valentin Haenel
Date: Thu, 21 Feb 2013 21:55:18 +0100
Subject: [PATCH 0120/1232] fix capitalization
---
docs/scenarios/scientific.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/scenarios/scientific.rst b/docs/scenarios/scientific.rst
index e6c0602d7..8164cd76c 100644
--- a/docs/scenarios/scientific.rst
+++ b/docs/scenarios/scientific.rst
@@ -42,7 +42,7 @@ signal processing.
Matplotlib
----------
-`matplotlib `_ is a flexible plotting
+`Matplotlib `_ is a flexible plotting
library for creating interactive 2D and 3D plots that can also be saved as
manuscript-quality figures. The API in many ways reflects that of `MATLAB `_,
easing transition of MATLAB users to Python. Many examples, along with the
From b7755bce6fc657c60db8da6147f7a71a9037e721 Mon Sep 17 00:00:00 2001
From: Valentin Haenel
Date: Thu, 21 Feb 2013 21:56:01 +0100
Subject: [PATCH 0121/1232] limit line length to 80
---
docs/scenarios/scientific.rst | 8 +++++---
1 file changed, 5 insertions(+), 3 deletions(-)
diff --git a/docs/scenarios/scientific.rst b/docs/scenarios/scientific.rst
index 8164cd76c..e91f096a5 100644
--- a/docs/scenarios/scientific.rst
+++ b/docs/scenarios/scientific.rst
@@ -44,9 +44,11 @@ Matplotlib
`Matplotlib `_ is a flexible plotting
library for creating interactive 2D and 3D plots that can also be saved as
-manuscript-quality figures. The API in many ways reflects that of `MATLAB `_,
-easing transition of MATLAB users to Python. Many examples, along with the
-source code to re-create them, can be browsed at the `matplotlib gallery `_.
+manuscript-quality figures. The API in many ways reflects that of `MATLAB
+`_, easing transition of MATLAB
+users to Python. Many examples, along with the source code to re-create them,
+can be browsed at the `matplotlib gallery
+`_.
Enthought
---------
From fadc69206a2522a6a6a73d7def5bb9dd042d17d0 Mon Sep 17 00:00:00 2001
From: Valentin Haenel
Date: Thu, 21 Feb 2013 21:56:28 +0100
Subject: [PATCH 0122/1232] insert whitespace after headings for source
coherence
---
docs/scenarios/scientific.rst | 2 ++
1 file changed, 2 insertions(+)
diff --git a/docs/scenarios/scientific.rst b/docs/scenarios/scientific.rst
index e91f096a5..1beb8fb46 100644
--- a/docs/scenarios/scientific.rst
+++ b/docs/scenarios/scientific.rst
@@ -19,6 +19,7 @@ Libraries
NumPy
-----
+
`NumPy `_ is a low level library written in C (and
FORTRAN) for high level mathematical functions. NumPy cleverly overcomes the
problem of running slower algorithms on Python by using multidimensional arrays
@@ -33,6 +34,7 @@ NumPy is compatible with Python versions 2.4 through to 2.7.2 and 3.1+.
SciPy
-----
+
`SciPy `_ is a library that uses Numpy for more mathematical
function. SciPy uses NumPy arrays as its basic data structure. SciPy comes with
modules for various commonly used tasks in scientific programing like linear
From 46d48e87484741bcba71acd306a7fc4c723f1c49 Mon Sep 17 00:00:00 2001
From: Valentin Haenel
Date: Thu, 21 Feb 2013 21:58:29 +0100
Subject: [PATCH 0123/1232] grammar and wording tweaks for the scipy
description
---
docs/scenarios/scientific.rst | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/docs/scenarios/scientific.rst b/docs/scenarios/scientific.rst
index 1beb8fb46..2e73971f7 100644
--- a/docs/scenarios/scientific.rst
+++ b/docs/scenarios/scientific.rst
@@ -36,10 +36,10 @@ SciPy
-----
`SciPy `_ is a library that uses Numpy for more mathematical
-function. SciPy uses NumPy arrays as its basic data structure. SciPy comes with
-modules for various commonly used tasks in scientific programing like linear
-algebra, integration (calculus), ordinary differential equation solvers and
-signal processing.
+functions. SciPy uses NumPy arrays as the basic data structure. SciPy comes
+with modules for various commonly used tasks in scientific programing, for
+example: linear algebra, integration (calculus), ordinary differential equation
+solvers and signal processing.
Matplotlib
----------
From 15394324a2e8c5fbb5c0af02854fd09f06e73c4a Mon Sep 17 00:00:00 2001
From: Valentin Haenel
Date: Thu, 21 Feb 2013 22:04:28 +0100
Subject: [PATCH 0124/1232] collect all Python distributions under 'Resources'
Also add a short section introduction about the purpose of this section.
---
docs/scenarios/scientific.rst | 31 +++++++++++++++++--------------
1 file changed, 17 insertions(+), 14 deletions(-)
diff --git a/docs/scenarios/scientific.rst b/docs/scenarios/scientific.rst
index 2e73971f7..3b1da876b 100644
--- a/docs/scenarios/scientific.rst
+++ b/docs/scenarios/scientific.rst
@@ -52,21 +52,17 @@ users to Python. Many examples, along with the source code to re-create them,
can be browsed at the `matplotlib gallery
`_.
-Enthought
----------
-
-Installing NumPy and SciPy can be a daunting task. Which is why the
-`Enthought Python distribution `_ was created. With
-Enthought, scientific python has never been easier (one click to install about
-100 scientific python packages). The Enthought Python Distribution comes in two
-variants: a free version `EPD Free `_
-and a paid version with various `pricing options.
-`_
-
-
Resources
:::::::::
+Installation of scientific Python packages can be troublesome. Many of these
+packages are implemented as Python C extensions which need to be compiled.
+This section lists various so-called Python distributions which provide precompiled and
+easy-to-install collections of scientific Python packages.
+
+Unofficial Windows Binaries for Python Extension Packages
+---------------------------------------------------------
+
Many people who do scientific computing are on Windows. And yet many of the
scientific computing packages are notoriously difficult to build and install.
`Christoph Gohlke `_ however, has
@@ -74,6 +70,13 @@ compiled a list of Windows binaries for many useful Python packages. The list
of packages has grown from a mainly scientific python resource to a more
general list. It might be a good idea to check it out if you're on Windows.
-For a quick introduction to scientific python:
+Enthought
+---------
-http://scipy-lectures.github.com
+Installing NumPy and SciPy can be a daunting task. Which is why the
+`Enthought Python distribution `_ was created. With
+Enthought, scientific python has never been easier (one click to install about
+100 scientific python packages). The Enthought Python Distribution comes in two
+variants: a free version `EPD Free `_
+and a paid version with various `pricing options.
+`_
From d73f3408a6faac34dde3636bd94cfe0e621feabb Mon Sep 17 00:00:00 2001
From: Valentin Haenel
Date: Thu, 21 Feb 2013 22:06:01 +0100
Subject: [PATCH 0125/1232] fix name of the EPD
---
docs/scenarios/scientific.rst | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/docs/scenarios/scientific.rst b/docs/scenarios/scientific.rst
index 3b1da876b..b0e62fb9d 100644
--- a/docs/scenarios/scientific.rst
+++ b/docs/scenarios/scientific.rst
@@ -70,8 +70,8 @@ compiled a list of Windows binaries for many useful Python packages. The list
of packages has grown from a mainly scientific python resource to a more
general list. It might be a good idea to check it out if you're on Windows.
-Enthought
----------
+Enthought Python Distribution (EPD)
+-----------------------------------
Installing NumPy and SciPy can be a daunting task. Which is why the
`Enthought Python distribution `_ was created. With
From 852f29d5681b1f414e679c4b3ab84f29a6b3e039 Mon Sep 17 00:00:00 2001
From: Valentin Haenel
Date: Thu, 21 Feb 2013 22:18:39 +0100
Subject: [PATCH 0126/1232] add Anaconda
---
docs/scenarios/scientific.rst | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/docs/scenarios/scientific.rst b/docs/scenarios/scientific.rst
index b0e62fb9d..2c515b070 100644
--- a/docs/scenarios/scientific.rst
+++ b/docs/scenarios/scientific.rst
@@ -80,3 +80,14 @@ Enthought, scientific python has never been easier (one click to install about
variants: a free version `EPD Free `_
and a paid version with various `pricing options.
`_
+
+Anaconda
+--------
+
+`Continuum Analytics `_ offers the `Anaconda
+Python Distribution `_ which
+includes all the common scientific python packages and additionally many
+packages related to data analytics and big data. Anaconda comes in two
+flavours, a paid for version and a completely free and open source community
+edition, Anaconda CE, which contains a slightly reduced feature set. Free
+licences for the paid-for version are available for academics and researchers.
From 9cbaf20138eadf745317010d7b1608225515beeb Mon Sep 17 00:00:00 2001
From: Valentin Haenel
Date: Thu, 21 Feb 2013 22:26:12 +0100
Subject: [PATCH 0127/1232] mention the Python Scientific Lecture Notes
---
docs/scenarios/scientific.rst | 9 ++++++---
1 file changed, 6 insertions(+), 3 deletions(-)
diff --git a/docs/scenarios/scientific.rst b/docs/scenarios/scientific.rst
index 2c515b070..a8cddde23 100644
--- a/docs/scenarios/scientific.rst
+++ b/docs/scenarios/scientific.rst
@@ -10,9 +10,12 @@ is widely used in academia and scientific projects because it is easy to write,
and it performs really well.
Due to its high performance nature, scientific computing in python often refers
-to external libraries, typically written in faster languages (like C, or FORTRAN
-for matrix operations). The main libraries used are `NumPy`_,
-`SciPy`_ and `Matplotlib`_.
+to external libraries, typically written in faster languages (like C, or
+FORTRAN for matrix operations). The main libraries used are `NumPy`_, `SciPy`_
+and `Matplotlib`_. Going into detail about these libraries is beyond the scope
+of the Python guide. However, a comprehensive introduction to the scientific
+Python ecosystem can be found in the `Python Scientific Lecture Notes
+`_
Libraries
:::::::::
From 8c15d01979a547d0687e99af83bbe0d1b5030570 Mon Sep 17 00:00:00 2001
From: lambdadi
Date: Wed, 6 Mar 2013 14:38:23 +0530
Subject: [PATCH 0128/1232] Fix markdown formatting mistakes
Markdown formatting, for text emphasis and file paths, was broken in my
previous commit to the 'Idioms' section of the style.rst document. My
previous commit may be found at:
https://github.com/kennethreitz/python-guide/pull/243
Sorry!
---
docs/writing/style.rst | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index f084d0b33..c24bb325a 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -251,13 +251,13 @@ is a probable indication that such a refactoring is needed.
Idioms
------
-A programming Idiom, put simply, is _a way_ to write code. The notion of programming Idioms
-is discussed amply at `c2 ` and at `Stack Overflow `.
+A programming Idiom, put simply, is a *way* to write code. The notion of programming Idioms
+is discussed amply at `c2 `_ and at `Stack Overflow `_.
Idiomatic Python code is often referred to as being *Pythonic*.
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.
Some common Python idioms follow:
From 8744a5243a1314a08061e3ae7b443552de5fff13 Mon Sep 17 00:00:00 2001
From: javex
Date: Fri, 8 Mar 2013 03:40:32 +0100
Subject: [PATCH 0129/1232] Add documentation for pyramid
---
docs/scenarios/web.rst | 16 +++++++++++++++-
1 file changed, 15 insertions(+), 1 deletion(-)
diff --git a/docs/scenarios/web.rst b/docs/scenarios/web.rst
index 7bdd1dd10..264d45085 100644
--- a/docs/scenarios/web.rst
+++ b/docs/scenarios/web.rst
@@ -90,7 +90,21 @@ application that is not commonly found in other web frameworks.
Support can be found on its `mailing list `_.
-.. todo:: Explain Pyramid
+Pyramid
+--------
+
+`Pyramid `_ lies somewhere between a big
+framework like Django and the microframeworks: It comes with a lot of libraries
+and functionality and can thus not be considered lightweight. On the other
+hand, it does not provide all the functionality Django does. Instead Pyramid
+brings basic support for most regular tasks and provides a great deal of
+extensibility. Additionally, Pyramid has a huge focus on complete
+`documentation `_. As
+a little extra it comes with the Werkzeug Debugger which allows you to debug a
+running web application in the browser.
+
+**Support** can also be found in the
+`documentation `_.
Web Servers
From 709f8d3451266b64a2c1533761a6987b6b7c5146 Mon Sep 17 00:00:00 2001
From: Eli
Date: Fri, 8 Mar 2013 16:55:48 -0500
Subject: [PATCH 0130/1232] Fix mispelling
---
docs/writing/style.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index c24bb325a..285d8ca6c 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -95,7 +95,7 @@ arguments, and in which order.
In those two cases, it is possible to use argument names when calling the functions
and, doing so, it is possible to switch the order of arguments, calling for instance
``send(recipient='World', message='Hello')`` and ``point(y=2, x=1)`` but this
-reduce readability and is unnecessarily verbose, compared to the more straightforward
+reduces readability and is unnecessarily verbose, compared to the more straightforward
calls to ``send('Hello', 'World')`` and ``point(1, 2)``.
**Keyword arguments** are not mandatory and have default values. They are often
From 50ccd6b6a91718035b51d9ebbabc0279d7636fad Mon Sep 17 00:00:00 2001
From: Kyle Kelley
Date: Mon, 18 Mar 2013 18:22:05 -0300
Subject: [PATCH 0131/1232] Grammar fix: s/it's current/it's currently
---
docs/starting/which-python.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/starting/which-python.rst b/docs/starting/which-python.rst
index ab5d9b97e..3a39b6634 100644
--- a/docs/starting/which-python.rst
+++ b/docs/starting/which-python.rst
@@ -69,7 +69,7 @@ PyPy aims for maximum compatibility with the reference CPython implementation
while improving performance.
If you are looking to squeeze more performance out of your Python code, it's
-worth giving PyPy a try. On a suite of benchmarks, it's current `over 5 times
+worth giving PyPy a try. On a suite of benchmarks, it's currently `over 5 times
faster than CPython `_.
Currently PyPy supports Python 2.7. [#pypy_ver]_
From 8ed7588716d3a83b9799dff65d5feb2731922d78 Mon Sep 17 00:00:00 2001
From: Kyle Kelley
Date: Mon, 18 Mar 2013 18:23:45 -0300
Subject: [PATCH 0132/1232] Grammar fixes
---
docs/starting/which-python.rst | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/docs/starting/which-python.rst b/docs/starting/which-python.rst
index 3a39b6634..2486528df 100644
--- a/docs/starting/which-python.rst
+++ b/docs/starting/which-python.rst
@@ -90,11 +90,11 @@ Currently Jython supports up to Python 2.5. [#jython_ver]_
IronPython
----------
-`IronPython `_ is an implementation of Python for .NET
+`IronPython `_ is an implementation of Python for the .NET
framework. It can use both Python and .NET framework libraries, and can also
expose Python code to other .NET languages.
-`Python Tools for Visual Studio `_ integrate
+`Python Tools for Visual Studio `_ integrates
IronPython directly in to the Visual Studio development environment, making it
an ideal choice for Windows developers.
From 1fb50a3999f62dc84b6989588a56cd3becc9e76a Mon Sep 17 00:00:00 2001
From: Kyle Kelley
Date: Mon, 18 Mar 2013 18:30:05 -0300
Subject: [PATCH 0133/1232] Made more direct and concise
The guide is opinionated, and that's ok.
---
docs/writing/structure.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index 456fd43af..cd647633a 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -91,7 +91,7 @@ environment, or your project's internal modules.
To keep in line with the style guide, keep module names short, lowercase, and
be sure to avoid using special symbols like the dot (.) or question mark (?).
-So a file name like `my.spam.py` is one you should try to avoid! Naming this way
+So a file name like `my.spam.py` is one you should avoid! Naming this way
will interfere with the way python looks for modules.
In this example python expects to find a "spam.py" file in a folder named "my"
From b9b50213bb84896f7f6300a3d50efaf3516294af Mon Sep 17 00:00:00 2001
From: Kyle Kelley
Date: Mon, 18 Mar 2013 18:46:08 -0300
Subject: [PATCH 0134/1232] Quick grammar fix
---
docs/writing/structure.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index cd647633a..001413948 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -281,7 +281,7 @@ Decorators
----------
The Python language provides a simple yet powerful syntax called 'decorators'.
-A decorator is a function or a class that wraps (or decorate) a function
+A decorator is a function or a class that wraps (or decorates) a function
or a method. The 'decorated' function or method will replace the original
'undecorated' function or method. Because functions are first-class objects
in Python, it can be done 'manually', but using the @decorator syntax is
From bc7799d1fad0ddc241ee021bd738197b9646d724 Mon Sep 17 00:00:00 2001
From: Kyle Kelley
Date: Mon, 18 Mar 2013 18:48:45 -0300
Subject: [PATCH 0135/1232] Separate join and list comprehension
---
docs/writing/structure.rst | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst
index 001413948..af388bc79 100644
--- a/docs/writing/structure.rst
+++ b/docs/writing/structure.rst
@@ -445,7 +445,8 @@ with calls to append().
.. code-block:: python
# create a concatenated string from 0 to 19 (e.g. "012..1819")
- print "".join([str(n) for n in range(20)])
+ nums = [str(n) for n in range(20)]
+ print "".join(nums)
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
From 810956c56b0266722433b935ca208f9bc4ce5847 Mon Sep 17 00:00:00 2001
From: Kyle Kelley
Date: Mon, 18 Mar 2013 19:06:50 -0300
Subject: [PATCH 0136/1232] Grammar: plurality fixes, tense fix, typos
---
docs/writing/style.rst | 28 ++++++++++++++--------------
1 file changed, 14 insertions(+), 14 deletions(-)
diff --git a/docs/writing/style.rst b/docs/writing/style.rst
index 285d8ca6c..dcfd145fe 100644
--- a/docs/writing/style.rst
+++ b/docs/writing/style.rst
@@ -10,8 +10,8 @@ recognised fact that code is read much more often than it is written.
One reason for Python code to be easily read and understood is its relatively
complete set of Code Style guidelines and "Pythonic" idioms.
-Moreover, when a veteran Python developer (a Pythonista) point to some
-parts of a code and say it is not "Pythonic", it usually means that these lines
+Moreover, when a veteran Python developer (a Pythonista) points to portions of code
+and says they are not "Pythonic", it usually means that these lines
of code do not follow the common guidelines and fail to express the intent in
what is considered the best (hear: most readable) way.
@@ -89,7 +89,7 @@ Arguments can be passed to functions in four different ways.
simplest form of arguments and they can be used for the few function arguments
that are fully part of the functions meaning and their order is natural. For
instance, in ``send(message, recipient)`` or ``point(x, y)`` the user of the
-function has no difficulty to remember that those two function require two
+function has no difficulty remembering that those two functions require two
arguments, and in which order.
In those two cases, it is possible to use argument names when calling the functions
@@ -103,7 +103,7 @@ used for optional parameters sent to the function. When a function has more than
two or three positional parameters, its signature will be more difficult to remember
and using keyword argument with default values is helpful. For instance, a more
complete ``send`` function could be defined as ``send(message, to, cc=None, bcc=None)``.
-Here ``cc`` and ``bcc`` are optional, and evaluate to ``None`` when the are not
+Here ``cc`` and ``bcc`` are optional, and evaluate to ``None`` when they are not
passed another value.
Calling a function with keyword arguments can be done in multiple ways in Python,
@@ -189,18 +189,18 @@ As seen above, Python allows many tricks, and some of them are potentially
dangerous. A good example is that any client code can override an object's
properties and methods: there is no "private" keyword in Python. This
philosophy, very different from highly defensive languages like Java, which
-give a lot of mechanism to prevent any misuse, is expressed by the saying: "We
+give a lot of mechanisms to prevent any misuse, is expressed by the saying: "We
are consenting adults".
This doesn't mean that, for example, no properties are considered private, and
that no proper encapsulation is possible in Python. But, instead of relying on
concrete walls erected by the developers between their code and other's, the
-Python community prefers to rely on a set of convention indicating that these
+Python community prefers to rely on a set of conventions indicating that these
elements should not be accessed directly.
The main convention for private properties and implementation details is to
prefix all "internals" with an underscore. If the client code breaks this rule
-and access to these marked elements, any misbehavior or problems encountered if
+and accesses these marked elements, any misbehavior or problems encountered if
the code is modified is the responsibility of the client code.
Using this convention generously is encouraged: any method or property that is
@@ -215,7 +215,7 @@ Returning values
When a function grows in complexity is not uncommon to use multiple return statements
inside the function's body. However, in order to keep a clear intent and a sustainable
readability level, it is preferable to avoid returning meaningful values from many
-output point in the body.
+output points in the body.
There are two main cases for returning values in a function: The result of the function
return when it has been processed normally, and the error cases that indicate a wrong
@@ -227,12 +227,12 @@ as None or False, indicating that the function could not perform correctly might
case, it is better to return as early as the incorrect context has been detected. It will
help to flatten the structure of the function: all the code after the return-because-of-error
statement can assume the condition is met to further compute the function's main result.
-Having multiple such return statement is often necessary.
+Having multiple such return statements is often necessary.
However, when a function has multiple main exit points for its normal course, it becomes
difficult to debug the returned result, and it may be preferable to keep a single exit
-point. This will also help factoring out some code paths, and the multiple exit point
-is a probable indication that such a refactoring is needed.
+point. This will also help factoring out some code paths, and the multiple exit points
+are a probable indication that such a refactoring is needed.
.. code-block:: python
@@ -351,7 +351,7 @@ Take the following code for example::
return 's' in l
Even though both functions look identical, because *lookup_dict* is utilizing the fact that dictionaries in python are hashtables, the lookup performance between the two is very different.
-Python will have to go through each item in the list to find a matching case, which is time consuming. By analysing the hash of the dictionary finding keys in the dict can be done very quickly.
+Python will have to go through each item in the list to find a matching case, which is time consuming. By analysing the hash of the dictionary, finding keys in the dict can be done very quickly.
For more information see this `StackOverflow `_ page.
Zen of Python
@@ -589,9 +589,9 @@ sometimes but is preferably avoided, because of its fragility: a white space
added to the end of the line, after the backslash, will break the code and may
have unexpected results.
-A preferred solution is to use parenthesis around your elements. Left with an
+A preferred solution is to use parentheses around your elements. Left with an
unclosed parenthesis on an end-of-line the Python interpreter will join the
-next line until the parenthesis is closed. The same behavior holds for curly
+next line until the parentheses are closed. The same behavior holds for curly
and square braces.
**Bad**:
From d6f214ade0c3daa65dde0015ae87c4c2092cd633 Mon Sep 17 00:00:00 2001
From: Kyle Kelley
Date: Thu, 21 Mar 2013 16:46:39 -0400
Subject: [PATCH 0137/1232] Grammar fix, added RabbitMQ to scenarios/client
---
docs/scenarios/admin.rst | 2 +-
docs/scenarios/cli.rst | 2 +-
docs/scenarios/client.rst | 6 ++++++
docs/scenarios/db.rst | 3 +--
4 files changed, 9 insertions(+), 4 deletions(-)
diff --git a/docs/scenarios/admin.rst b/docs/scenarios/admin.rst
index 042f703ae..3397d6632 100644
--- a/docs/scenarios/admin.rst
+++ b/docs/scenarios/admin.rst
@@ -104,7 +104,7 @@ The following command lists all available minions running CentOS using the grain
Salt also provides a state system. States can be used to configure the minion hosts.
-For example, when a minion host is ordered to read the following state file, will install
+For example, when a minion host is ordered to read the following state file, it will install
and start the Apache server:
.. code-block:: yaml
diff --git a/docs/scenarios/cli.rst b/docs/scenarios/cli.rst
index cea7a3f6c..bc952c74f 100644
--- a/docs/scenarios/cli.rst
+++ b/docs/scenarios/cli.rst
@@ -6,4 +6,4 @@ Command Line Applications
Clint
-----
-.. todo:: Write about Clint
\ No newline at end of file
+.. todo:: Write about Clint
diff --git a/docs/scenarios/client.rst b/docs/scenarios/client.rst
index e2d82029a..b9cd4023b 100644
--- a/docs/scenarios/client.rst
+++ b/docs/scenarios/client.rst
@@ -41,3 +41,9 @@ messaging library aimed at use in scalable distributed or concurrent
applications. It provides a message queue, but unlike message-oriented
middleware, a ØMQ system can run without a dedicated message broker. The
library is designed to have a familiar socket-style API.
+
+RabbitMQ
+--------
+
+.. todo:: Write about RabbitMQ
+
diff --git a/docs/scenarios/db.rst b/docs/scenarios/db.rst
index 4f03058c2..d3c398f82 100644
--- a/docs/scenarios/db.rst
+++ b/docs/scenarios/db.rst
@@ -30,7 +30,6 @@ Django ORM
The Django ORM is the interface used by `Django `_
to provide database access.
-It's based on the idea of models, an abstraction that makes it easier to
+It's based on the idea of `models `_, an abstraction that makes it easier to
manipulate data in Python.
-Documentation can be found `here `_
\ No newline at end of file
From 5337437d530a8c3687f45479a0b6503f12372151 Mon Sep 17 00:00:00 2001
From: Kyle Kelley
Date: Thu, 21 Mar 2013 16:51:13 -0400
Subject: [PATCH 0138/1232] Grammar fix, embed Kivy link
---
docs/scenarios/gui.rst | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/docs/scenarios/gui.rst b/docs/scenarios/gui.rst
index d40ac7e7f..49dd0ad5e 100644
--- a/docs/scenarios/gui.rst
+++ b/docs/scenarios/gui.rst
@@ -41,7 +41,7 @@ Gtk
PyGTK provides Python bindings for the GTK+ toolkit. Like the GTK+ library
itself, it is currently licensed under the GNU LGPL. It is worth noting that
PyGTK only currently supports the Gtk-2.X API (NOT Gtk-3.0). It is currently
-recommended that PyGTK is not used for new projects and existing applications
+recommended that PyGTK not be used for new projects and existing applications
be ported from PyGTK to PyGObject.
Tk
@@ -60,10 +60,10 @@ available on the `Python Wiki `_.
Kivy
----
-Kivy is a Python library for development of multi-touch enabled media rich applications. The aim is to allow for quick and easy interaction design and rapid prototyping, while making your code reusable and deployable.
+`Kivy `_ is a Python library for development of multi-touch enabled media rich applications. The aim is to allow for quick and easy interaction design and rapid prototyping, while making your code reusable and deployable.
Kivy is written in Python, based on OpenGL and supports different input devices such as: Mouse, Dual Mouse, TUIO, WiiMote, WM_TOUCH, HIDtouch, Apple's products and so on.
Kivy is actively being developed by a community and free to use. It operates on all major platforms (Linux, OSX, Windows, Android).
-The main resource for information is the website: http://kivy.org
\ No newline at end of file
+The main resource for information is the website: http://kivy.org
From c0d897d45e178f16f30926f8f1de6054b597a677 Mon Sep 17 00:00:00 2001
From: Kyle Kelley
Date: Thu, 21 Mar 2013 17:06:29 -0400
Subject: [PATCH 0139/1232] Little grammar fix, trailing whitespace deleted
---
docs/scenarios/imaging.rst | 4 ++--
docs/scenarios/network.rst | 8 ++++----
2 files changed, 6 insertions(+), 6 deletions(-)
diff --git a/docs/scenarios/imaging.rst b/docs/scenarios/imaging.rst
index 8a1597221..8defa0b73 100644
--- a/docs/scenarios/imaging.rst
+++ b/docs/scenarios/imaging.rst
@@ -12,7 +12,7 @@ The `Python Imaging Library `_, or PIL
for short, is *the* library for image manipulation in Python.
It works with Python 1.5.2 and above, including 2.5, 2.6 and 2.7. Unfortunately,
-it doesn't work with 3.0+ yet.
+it doesn't work with 3.0+ yet.
Installation
~~~~~~~~~~~~
@@ -20,7 +20,7 @@ Installation
PIL has a reputation of not being very straightforward to install. Listed below
are installation notes on various systems.
-Also, there's a fork named `Pillow `_ which is easier
+Also, there's a fork named `Pillow `_ which is easier
to install. It has good setup instructions for all platforms.
Installing on Linux
diff --git a/docs/scenarios/network.rst b/docs/scenarios/network.rst
index 0521089ed..6b05a5f6e 100644
--- a/docs/scenarios/network.rst
+++ b/docs/scenarios/network.rst
@@ -6,19 +6,19 @@ Twisted
`Twisted `_ is an event-driven networking engine. It can be
used to build applications around many different networking protocols, including http servers
-and clients, applications using SMTP, POP3, IMAP or SSH protocols, instant messaging and
-`many more `_.
+and clients, applications using SMTP, POP3, IMAP or SSH protocols, instant messaging and
+many more `_.
PyZMQ
-----
`PyZMQ `_ is the Python binding for `ZeroMQ `_,
which is a high-performance asynchronous messaging library. One great advantage is that ZeroMQ
-can be used for message queuing without message broker. The basic patterns for this are:
+can be used for message queuing without a message broker. The basic patterns for this are:
- request-reply: connects a set of clients to a set of services. This is a remote procedure call
and task distribution pattern.
-- publish-subscribe: connects a set of publishers to a set of subscribers. This is a data
+- publish-subscribe: connects a set of publishers to a set of subscribers. This is a data
distribution pattern.
- push-pull (or pipeline): connects nodes in a fan-out / fan-in pattern that can have multiple
steps, and loops. This is a parallel task distribution and collection pattern.
From a899f414f446a6e787b87caf4d73e41191338991 Mon Sep 17 00:00:00 2001
From: Kyle Kelley
Date: Thu, 21 Mar 2013 17:09:18 -0400
Subject: [PATCH 0140/1232] Used U.S. English spelling to keep the guide
consistent
---
docs/scenarios/scientific.rst | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/docs/scenarios/scientific.rst b/docs/scenarios/scientific.rst
index a8cddde23..b83f90131 100644
--- a/docs/scenarios/scientific.rst
+++ b/docs/scenarios/scientific.rst
@@ -60,7 +60,7 @@ Resources
Installation of scientific Python packages can be troublesome. Many of these
packages are implemented as Python C extensions which need to be compiled.
-This section lists various so-called Python distributions which provide precompiled and
+This section lists various so-called Python distributions which provide precompiled and
easy-to-install collections of scientific Python packages.
Unofficial Windows Binaries for Python Extension Packages
@@ -91,6 +91,6 @@ Anaconda
Python Distribution `_ which
includes all the common scientific python packages and additionally many
packages related to data analytics and big data. Anaconda comes in two
-flavours, a paid for version and a completely free and open source community
+flavors, a paid for version and a completely free and open source community
edition, Anaconda CE, which contains a slightly reduced feature set. Free
-licences for the paid-for version are available for academics and researchers.
+licenses for the paid-for version are available for academics and researchers.
From 7ec689f4bf5e0dd8f8b5c0cadb48a7bb48ca58ba Mon Sep 17 00:00:00 2001
From: Kyle Kelley
Date: Thu, 21 Mar 2013 17:19:00 -0400
Subject: [PATCH 0141/1232] Grammar fix, got rid of DOS line endings
---
docs/scenarios/scrape.rst | 200 +++++++++++++++++++-------------------
1 file changed, 101 insertions(+), 99 deletions(-)
diff --git a/docs/scenarios/scrape.rst b/docs/scenarios/scrape.rst
index 17a028129..b4f10b2fa 100644
--- a/docs/scenarios/scrape.rst
+++ b/docs/scenarios/scrape.rst
@@ -1,99 +1,101 @@
-HTML Scraping
-=============
-
-Web Scraping
-------------
-
-Web sites are written using HTML, which means that each web page is a
-structured document. Sometimes it would be great to obtain some data from
-them and preserve the structure while we're at it. Web sites provide
-don't always provide their data in comfortable formats such as ``.csv``.
-
-This is where web scraping comes in. Web scraping is the practice of using a
-computer program to sift through a web page and gather the data that you need
-in a format most useful to you while at the same time preserving the structure
-of the data.
-
-lxml and Requests
------------------
-
-`lxml `_ is a pretty extensive library written for parsing
-XML and HTML documents really fast. It even handles messed up tags. We will
-also be using the `Requests `_ module instead of the already built-in urlib2
-due to improvements in speed and readability. You can easily install both
-using ``pip install lxml`` and ``pip install requests``.
-
-Lets start with the imports:
-
-.. code-block:: python
-
- from lxml import html
- import requests
-
-Next we will use ``requests.get`` to retrieve the web page with our data
-and parse it using the ``html`` module and save the results in ``tree``:
-
-.. code-block:: python
-
- page = requests.get('http://econpy.pythonanywhere.com/ex/001.html')
- tree = html.fromstring(page.text)
-
-``tree`` now contains the whole HTML file in a nice tree structure which
-we can go over two different ways: XPath and CSSSelect. In this example, I
-will focus on the former.
-
-XPath is a way of locating information in structured documents such as
-HTML or XML documents. A good introduction to XPath is on `W3Schools `_ .
-
-There are also various tools for obtaining the XPath of elements such as
-FireBug for Firefox or if you're using Chrome you can right click an
-element, choose 'Inspect element', highlight the code and then right
-click again and choose 'Copy XPath'.
-
-After a quick analysis, we see that in our page the data is contained in
-two elements - one is a div with title 'buyer-name' and the other is a
-span with class 'item-price':
-
-::
-
- Carson Busses
- $29.95
-
-Knowing this we can create the correct XPath query and use the lxml
-``xpath`` function like this:
-
-.. code-block:: python
-
- #This will create a list of buyers:
- buyers = tree.xpath('//div[@title="buyer-name"]/text()')
- #This will create a list of prices
- prices = tree.xpath('//span[@class="item-price"]/text()')
-
-Lets see what we got exactly:
-
-.. code-block:: python
-
- print 'Buyers: ', buyers
- print 'Prices: ', prices
-
-::
-
- Buyers: ['Carson Busses', 'Earl E. Byrd', 'Patty Cakes',
- 'Derri Anne Connecticut', 'Moe Dess', 'Leda Doggslife', 'Dan Druff',
- 'Al Fresco', 'Ido Hoe', 'Howie Kisses', 'Len Lease', 'Phil Meup',
- 'Ira Pent', 'Ben D. Rules', 'Ave Sectomy', 'Gary Shattire',
- 'Bobbi Soks', 'Sheila Takya', 'Rose Tattoo', 'Moe Tell']
-
- Prices: ['$29.95', '$8.37', '$15.26', '$19.25', '$19.25',
- '$13.99', '$31.57', '$8.49', '$14.47', '$15.86', '$11.11',
- '$15.98', '$16.27', '$7.50', '$50.85', '$14.26', '$5.68',
- '$15.00', '$114.07', '$10.09']
-
-Congratulations! We have successfully scraped all the data we wanted from
-a web page using lxml and Requests. We have it stored in memory as two
-lists. Now we can do all sorts of cool stuff with it: we can analyze it
-using Python or we can save it a file and share it with the world.
-
-A cool idea to think about is modifying this script to iterate through
-the rest of the pages of this example dataset or rewriting this
-application to use threads for improved speed.
+HTML Scraping
+=============
+
+Web Scraping
+------------
+
+Web sites are written using HTML, which means that each web page is a
+structured document. Sometimes it would be great to obtain some data from
+them and preserve the structure while we're at it. Web sites don't always
+provide their data in comfortable formats such as ``csv`` or ``json``.
+
+This is where web scraping comes in. Web scraping is the practice of using a
+computer program to sift through a web page and gather the data that you need
+in a format most useful to you while at the same time preserving the structure
+of the data.
+
+lxml and Requests
+-----------------
+
+`lxml `_ is a pretty extensive library written for parsing
+XML and HTML documents really fast. It even handles messed up tags. We will
+also be using the `Requests `_
+module instead of the already built-in urlib2 due to improvements in speed and
+readability. You can easily install both using ``pip install lxml`` and
+``pip install requests``.
+
+Lets start with the imports:
+
+.. code-block:: python
+
+ from lxml import html
+ import requests
+
+Next we will use ``requests.get`` to retrieve the web page with our data
+and parse it using the ``html`` module and save the results in ``tree``:
+
+.. code-block:: python
+
+ page = requests.get('http://econpy.pythonanywhere.com/ex/001.html')
+ tree = html.fromstring(page.text)
+
+``tree`` now contains the whole HTML file in a nice tree structure which
+we can go over two different ways: XPath and CSSSelect. In this example, I
+will focus on the former.
+
+XPath is a way of locating information in structured documents such as
+HTML or XML documents. A good introduction to XPath is on
+`W3Schools `_ .
+
+There are also various tools for obtaining the XPath of elements such as
+FireBug for Firefox or the Chrome Inspector. If you're using Chrome, you
+can right click an element, choose 'Inspect element', highlight the code,
+right click again and choose 'Copy XPath'.
+
+After a quick analysis, we see that in our page the data is contained in
+two elements - one is a div with title 'buyer-name' and the other is a
+span with class 'item-price':
+
+::
+
+ Carson Busses
+ $29.95
+
+Knowing this we can create the correct XPath query and use the lxml
+``xpath`` function like this:
+
+.. code-block:: python
+
+ #This will create a list of buyers:
+ buyers = tree.xpath('//div[@title="buyer-name"]/text()')
+ #This will create a list of prices
+ prices = tree.xpath('//span[@class="item-price"]/text()')
+
+Lets see what we got exactly:
+
+.. code-block:: python
+
+ print 'Buyers: ', buyers
+ print 'Prices: ', prices
+
+::
+
+ Buyers: ['Carson Busses', 'Earl E. Byrd', 'Patty Cakes',
+ 'Derri Anne Connecticut', 'Moe Dess', 'Leda Doggslife', 'Dan Druff',
+ 'Al Fresco', 'Ido Hoe', 'Howie Kisses', 'Len Lease', 'Phil Meup',
+ 'Ira Pent', 'Ben D. Rules', 'Ave Sectomy', 'Gary Shattire',
+ 'Bobbi Soks', 'Sheila Takya', 'Rose Tattoo', 'Moe Tell']
+
+ Prices: ['$29.95', '$8.37', '$15.26', '$19.25', '$19.25',
+ '$13.99', '$31.57', '$8.49', '$14.47', '$15.86', '$11.11',
+ '$15.98', '$16.27', '$7.50', '$50.85', '$14.26', '$5.68',
+ '$15.00', '$114.07', '$10.09']
+
+Congratulations! We have successfully scraped all the data we wanted from
+a web page using lxml and Requests. We have it stored in memory as two
+lists. Now we can do all sorts of cool stuff with it: we can analyze it
+using Python or we can save it to a file and share it with the world.
+
+A cool idea to think about is modifying this script to iterate through
+the rest of the pages of this example dataset or rewriting this
+application to use threads for improved speed.
From 3042e0844872b6305ca0b8c52543efda1948b87c Mon Sep 17 00:00:00 2001
From: Kyle Kelley
Date: Thu, 21 Mar 2013 17:21:33 -0400
Subject: [PATCH 0142/1232] Added section for Numba
---
docs/scenarios/scientific.rst | 9 +++++++--
1 file changed, 7 insertions(+), 2 deletions(-)
diff --git a/docs/scenarios/scientific.rst b/docs/scenarios/scientific.rst
index b83f90131..49d5c88c6 100644
--- a/docs/scenarios/scientific.rst
+++ b/docs/scenarios/scientific.rst
@@ -35,6 +35,10 @@ people who only need the basic requirements can just use NumPy.
NumPy is compatible with Python versions 2.4 through to 2.7.2 and 3.1+.
+Numba
+-----
+.. todo:: Write about Numba
+
SciPy
-----
@@ -60,8 +64,9 @@ Resources
Installation of scientific Python packages can be troublesome. Many of these
packages are implemented as Python C extensions which need to be compiled.
-This section lists various so-called Python distributions which provide precompiled and
-easy-to-install collections of scientific Python packages.
+This section lists various so-called scientific Python distributions which
+provide precompiled and easy-to-install collections of scientific Python
+packages.
Unofficial Windows Binaries for Python Extension Packages
---------------------------------------------------------
From d3ed3cf9ce08eee36be4cd78e5cc9503642ae06e Mon Sep 17 00:00:00 2001
From: Kyle Kelley
Date: Thu, 21 Mar 2013 17:23:13 -0400
Subject: [PATCH 0143/1232] Fixed typos/spelling errors in scenarios/speed
---
docs/scenarios/speed.rst | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/docs/scenarios/speed.rst b/docs/scenarios/speed.rst
index 87a1f66f6..8c8ec5021 100644
--- a/docs/scenarios/speed.rst
+++ b/docs/scenarios/speed.rst
@@ -42,7 +42,7 @@ The GIL
`The GIL`_ (Global Interpreter Lock) is how Python allows multiple threads to
operate at the same time. Python's memory management isn't entirely thread-safe,
-so the GIL is required to prevents multiple threads from running the same
+so the GIL is required to prevent multiple threads from running the same
Python code at once.
David Beazley has a great `guide`_ on how the GIL operates. He also covers the
@@ -58,8 +58,8 @@ C Extensions
The GIL
-------
-`Special care`_ must be taken when writing C extensions to make sure you r
-egister your threads with the interpreter.
+`Special care`_ must be taken when writing C extensions to make sure you
+register your threads with the interpreter.
C Extensions
::::::::::::
@@ -86,7 +86,7 @@ Threading
---------
-Spanwing Processes
+Spawning Processes
------------------
From 92e27e3a8cad3c618bc2991d59c9b1e337993641 Mon Sep 17 00:00:00 2001
From: Kyle Kelley