Merge pull request #393 from Zearin/code-blocks

Code blocks
This commit is contained in:
Ian Cordasco
2014-04-01 21:02:57 -05:00
16 changed files with 119 additions and 80 deletions
+10 -9
View File
@@ -16,17 +16,18 @@ basis.
Topics include:
- Platform/version specific installations
- Platform- and version-specific installations
- Py2app, Py2exe, bbfreeze, pyInstaller
- Pip / virtualenv
- Documentation. Writing it.
- server configurations / tools for various web frameworks
- Pip
- Virtualenv
- fabric
- exhaustive module recommendations, grouped by topic/purpose
- Testing. Jenkins + tox guides.
- How to interface w/ hg from git easily
- what libraries to use for what
- Exhaustive module recommendations, grouped by topic/purpose
- Which libraries to use for what
- Server configurations & tools for various web frameworks
- Documentation: writing it
- Testing: Jenkins & tox guides
- How to easily interface ``hg`` from ``git`` easily
If you are not fond of reading reStructuredText, there is an
If you aren't fond of reading reStructuredText, there is an
almost up-to-date `HTML version at docs.python-guide.org
<http://docs.python-guide.org>`_.
+35 -25
View File
@@ -16,7 +16,7 @@ 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 line-wrapping to values compliant with
:pep:`8`. In your home directory, open a file called `.vimrc` and add the
:pep:`8`. In your home directory, open a file called ``.vimrc`` and add the
following lines::
set textwidth=79 " lines longer than 79 columns will be broken
@@ -42,11 +42,11 @@ If your VIM is compiled with `+python` you can also utilize some very handy
plugins to do these checks from within the editor.
For PEP8 checking, install the vim-pep8_ plugin, and for pyflakes you can
install vim-pyflakes_. Now you can map the functions `Pep8()` or `Pyflakes()`
install vim-pyflakes_. Now you can map the functions ``Pep8()`` or ``Pyflakes()``
to any hotkey or action you want in Vim. Both plugins will display errors at
the bottom of the screen, and provide an easy way to jump to the corresponding
line. It's very handy to call these functions whenever you save a file. In
order to do this, add the following lines to your `vimrc`::
order to do this, add the following lines to your ``.vimrc``::
autocmd BufWritePost *.py call Pyflakes()
autocmd BufWritePost *.py call Pep8()
@@ -67,12 +67,12 @@ Python-mode
Python-mode_ is a complex solution in VIM for working with Python code.
It has:
- Asynchronous Python code checking (pylint, pyflakes, pep8, mccabe) in any combination
- Asynchronous Python code checking (``pylint``, ``pyflakes``, ``pep8``, ``mccabe``) in any combination
- Code refactoring and autocompletion with Rope
- Fast Python folding
- Virtualenv support
- Search by Python documentation and run Python code
- Auto PEP8 error fixes
- Auto PEP8_ error fixes
And more.
@@ -105,10 +105,10 @@ already an Emacs user is `Python Programming in Emacs`_ at EmacsWiki.
TextMate
--------
"`TextMate <http://macromates.com/>`_ brings Apple's approach to operating
systems into the world of text editors. By bridging UNIX underpinnings and GUI,
TextMate cherry-picks the best of both worlds to the benefit of expert
scripters and novice users alike."
`TextMate <http://macromates.com/>`_ brings Apple's approach to operating
systems into the world of text editors. By bridging UNIX underpinnings and GUI,
TextMate cherry-picks the best of both worlds to the benefit of expert
scripters and novice users alike.
Sublime Text
------------
@@ -143,7 +143,7 @@ The most popular Eclipse plugin for Python development is Aptana's
Komodo IDE
----------
`Komodo IDE <http://www.activestate.com/komodo-ide>`_ is developed by
ActiveState and is a commercial IDE for Windows, Mac and Linux.
ActiveState and is a commercial IDE for Windows, Mac, and Linux.
Spyder
@@ -189,18 +189,22 @@ virtualenv
Virtualenv is a tool to keep the dependencies required by different projects
in separate places, by creating virtual Python environments for them.
It solves the "Project X depends on version 1.x but, Project Y needs 4.x"
dilemma and keeps your global site-packages directory clean and manageable.
dilemma, and keeps your global site-packages directory clean and manageable.
`virtualenv <http://www.virtualenv.org/en/latest/index.html>`_ creates
a folder which contains all the necessary executables to contain the
packages that a Python project would need. An example workflow is given.
Install virtualenv::
Install virtualenv:
.. code-block:: console
$ pip install virtualenv
Create a virtual environment for a project::
Create a virtual environment for a project:
.. code-block:: console
$ cd my_project
$ virtualenv venv
@@ -211,7 +215,9 @@ library which you can use to install other packages. The name of the
virtual environment (in this case, it was ``venv``) can be anything;
omitting the name will place the files in the current directory instead.
To start using the virtual environment, run::
To start using the virtual environment, run:
.. code-block:: console
$ source venv/bin/activate
@@ -219,14 +225,18 @@ To start using the virtual environment, run::
The name of the current virtual environment will now appear on the left
of the prompt (e.g. ``(venv)Your-Computer:your_project UserName$``) to
let you know that it's active. From now on, any package that you install
using ``pip`` will be placed in the venv folder, isolated from the global
Python installation. Install packages as usual::
using ``pip`` will be placed in the ``venv`` folder, isolated from the global
Python installation.
Install packages as usual:
.. code-block:: console
$ pip install requests
To stop using an environment simply type ``deactivate``. To remove the
To stop using an environment, simply type ``deactivate``. To remove the
environment, just remove the directory it was installed into. (In this
case, it would be ``rm -rf venv``).
case, it would be ``rm -rf venv``.)
Other Notes
^^^^^^^^^^^
@@ -239,7 +249,7 @@ for keeping the package list clean in case it needs to be accessed 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
::
.. code-block:: console
$ pip freeze > requirements.txt
@@ -249,7 +259,7 @@ versions. Later, when a different developer (or you, if you need to re-
create the environment) can install the same packages, with the same
versions by running
::
.. code-block:: console
$ pip install -r requirements.txt
@@ -265,14 +275,14 @@ virtualenvwrapper
`Virtualenvwrapper <http://pypi.python.org/pypi/virtualenvwrapper>`_ makes
virtualenv a pleasure to use by wrapping the command line API with a nicer CLI.
::
.. code-block:: console
$ pip install virtualenvwrapper
Put this into your `~/.bash_profile` (Linux/Mac) file:
Put this into your ``~/.bash_profile`` (Linux/Mac) file:
::
.. code-block:: console
$ export VIRTUALENVWRAPPER_VIRTUALENV_ARGS='--no-site-packages'
@@ -312,7 +322,7 @@ most out of using Python interactively. Its main components are:
* Flexible, embeddable interpreters to load into your own projects.
* Tools for high level and interactive parallel computing.
::
.. code-block:: console
$ pip install ipython
@@ -333,7 +343,7 @@ Python interpreter for Unix-like operating systems. It has the following feature
* Auto-indentation.
* Python 3 support.
::
.. code-block:: console
$ pip install bpython
+2 -1
View File
@@ -8,7 +8,8 @@ The Hitchhiker's Guide to Python!
Welcome to The Hitchhiker's Guide to Python.
**This guide is currently under heavy active development.** If you'd like to help, `fork us on GitHub <https://github.com/kennethreitz/python-guide>`_!
**This guide is currently under heavy active development.** If you'd like to help,
`fork us on GitHub <https://github.com/kennethreitz/python-guide>`_!
This *opinionated* guide exists to provide both novice and expert Python
developers a best-practice handbook to the installation, configuration, and
+12 -10
View File
@@ -7,14 +7,14 @@ 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
* **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
* **extensive standard libraries and third party modules for virtually
any task**
Python is sometimes described with the words "batteries included"
for its extensive
@@ -30,7 +30,7 @@ include:
the `Django <http://www.djangoproject.com>`_ web framework and the
`NumPy <http://numpy.scipy.org>`_ set of math routines.
* integration with other systems
* **integration with other systems**
Python can integrate with `Java libraries <http://www.jython.org>`_,
enabling it to be used with the rich Java environment that corporate
@@ -38,13 +38,13 @@ include:
`extended by C or C++ modules <http://docs.python.org/extending/>`_
when speed is of the essence.
* ubiquity on computers
* **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
* **friendly community**
Python has a vibrant and large :ref:`community <the-community>`
which maintains wikis, conferences, countless repositories,
@@ -77,10 +77,12 @@ 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.
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.
+2 -2
View File
@@ -30,8 +30,8 @@ Strive to keep any contributions relevant to the :ref:`purpose of The Guide
* `Cite <http://sphinx.pocoo.org/rest.html?highlight=citations#citations>`_
references where needed.
* If a subject isn't directly relevant to Python, but useful in conjunction
with Python (ex: Git, Github, Databases), reference by linking to useful
resources and describe why it's useful to Python.
with Python (e.g., Git, GitHub, Databases), reference by linking to useful
resources, and describe why it's useful to Python.
* When in doubt, ask.
Headings
+1 -1
View File
@@ -21,7 +21,7 @@ latter will ssh into each server, cd to our project directory, activate the
virtual environment, pull the newest codebase, and restart the application
server.
::
.. code-block:: python
from fabric.api import cd, env, prefix, run, task
+2 -2
View File
@@ -20,9 +20,9 @@ SQLAlchemy
Unlike many database libraries it not only provides an ORM layer but also a
generalized API for writing database-agnostic code without SQL.
::
.. code-block:: console
pip install sqlalchemy
$ pip install sqlalchemy
Django ORM
----------
+1 -1
View File
@@ -23,6 +23,6 @@ the instructions for your platform `here <https://pypi.python.org/pypi/Pillow/2.
After that, it's straightforward:
.. code-block:: bash
.. code-block:: console
$ pip install Pillow
+1 -1
View File
@@ -56,7 +56,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-block:: html
<div title="buyer-name">Carson Busses</div>
<span class="item-price">$29.95</span>
+17 -12
View File
@@ -8,9 +8,9 @@ Using a slightly modified version of `David Beazleys`_ CPU bound test code
(added loop for multiple tests), you can see the difference between CPython
and PyPy's processing.
::
.. code-block:: console
PyPy
# PyPy
$ ./pypy -V
Python 2.7.1 (7773f8fc4223, Nov 18 2011, 18:47:10)
[PyPy 1.7.0 with GCC 4.4.3]
@@ -21,9 +21,9 @@ and PyPy's processing.
0.0440690517426
0.0695300102234
::
.. code-block:: console
CPython
# CPython
$ ./python -V
Python 2.7.1
$ ./python measure2.py
@@ -72,9 +72,10 @@ Cython
with which you are able to write C and C++ modules for Python. Cython also
allows you to call functions from compiled C libraries. Using Cython allows
you to take advantage of Python's strong typing of variables and operations.
Here is an example of strong typing with Cython:
.. code-block:: python
Here's an example of strong typing with Cython:
.. code-block:: cython
def primes(int kmax):
"""Calculation of prime numbers with additional
@@ -128,7 +129,7 @@ Notice that in the Cython version you declare integers and integer arrays for
to be compiled into C types while also creating a Python list:
.. code-block:: python
.. code-block:: cython
def primes(int kmax):
"""Calculation of prime numbers with additional
@@ -190,18 +191,22 @@ The `pyximport` module allows you to import `pyx` files (e.g., `primesCy.pyx`) w
The `pyximport.install()` command allows the Python interpreter to start the Cython compiler directly to generate C-code,
which is automatically compiled to a `*.so` C-library. Cython is able to import this library for you in your Python-code.
Very easy and very efficient. With the `time.time()` function you are able to compare the time between this 2 different calls to find 500 prime numbers.
On a standard notebook (dual core AMD E-450 1.6 GHz), the measured values are:
On a standard notebook (dualcore AMD E-450 1,6 GHz) the measured values are:
.. code-block:: console
Cython time: 0.0054 seconds
Python time: 0.0566 seconds
Cython time: 0.0054 seconds
Python time: 0.0566 seconds
And here the output of an embedded `ARM beaglebone <http://beagleboard.org/Products/BeagleBone>`_ machine:
.. code-block:: console
Cython time: 0.0196 seconds
Cython time: 0.0196 seconds
Python time: 0.3302 seconds
Python time: 0.3302 seconds
Pyrex
-----
+5 -1
View File
@@ -59,6 +59,8 @@ Prerequisite is to install :ref:`Python on Windows <install-windows>`.
2. Write setup.py (`List of configuration options <http://www.py2exe.org/index.cgi/ListOfOptions>`_)::
.. code-block:: python
from distutils.core import setup
import py2exe
@@ -70,7 +72,9 @@ Prerequisite is to install :ref:`Python on Windows <install-windows>`.
4. (Optionally) `one-file mode <http://stackoverflow.com/questions/112698/py2exe-generate-single-executable-file#113014>`_
5. Generate `.exe` into `dist` directory::
5. Generate ``.exe`` into ``dist`` directory:
.. code-block:: console
$ python setup.py py2exe
+3 -1
View File
@@ -53,7 +53,9 @@ line at the bottom of your ``~/.bashrc`` file
export PATH=/usr/local/bin:/usr/local/sbin:$PATH
Now, we can install Python 2.7: ::
Now, we can install Python 2.7:
.. code-block:: console
$ brew install python
+5 -1
View File
@@ -25,9 +25,13 @@ tedious, so add the directories for your default Python version to the PATH.
Assuming that your Python installation is in ``C:\Python27\``, add this to your
PATH::
.. code-block:: console
C:\Python27\;C:\Python27\Scripts\
You can do this easily by running the following in ``powershell``::
You can do this easily by running the following in ``powershell``:
.. code-block:: console
[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27\;C:\Python27\Scripts\", "User")
+6 -2
View File
@@ -100,7 +100,9 @@ code easier to understand. In Python, comments begin with a hash
.. _docstring-ref:
In Python, *docstrings* describe modules, classes, and functions: ::
In Python, *docstrings* describe modules, classes, and functions:
.. code-block:: python
def square_and_rooter(x):
"""Returns the square root of self times self."""
@@ -130,7 +132,9 @@ 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: ::
*operation* of the function or class:
.. code-block:: python
# This function slows down program execution for some reason.
def square_and_rooter(x):
+10 -5
View File
@@ -336,7 +336,9 @@ Instead, use a list comprehension:
four_lists = [[] for __ in xrange(4)]
A common idiom for creating strings is to use :py:meth:`str.join` on an empty string.::
A common idiom for creating strings is to use :py:meth:`str.join` on an empty string.
.. code-block:: python
letters = ['s', 'p', 'a', 'm']
word = ''.join(letters)
@@ -345,7 +347,9 @@ 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::
Take the following code for example:
.. code-block:: python
d = {'s': [], 'p': [], 'a': [], 'm': []}
l = ['s', 'p', 'a', 'm']
@@ -365,7 +369,7 @@ Zen of Python
Also known as :pep:`20`, the guiding principles for Python's design.
::
.. code-block:: pycon
>>> import this
The Zen of Python, by Tim Peters
@@ -406,14 +410,15 @@ exists a command-line program, `pep8 <https://github.com/jcrocholl/pep8>`_,
that can check your code for conformance. Install it by running the following
command in your Terminal:
::
.. code-block:: console
$ pip install pep8
Then run it on a file or series of files to get a report of any violations.
::
.. code-block:: console
$ pep8 optparse.py
optparse.py:69:11: E401 multiple imports on one line
+7 -6
View File
@@ -81,7 +81,7 @@ series of tools.
Creating testcases is accomplished by subclassing a TestCase base class
::
.. code-block:: python
import unittest
@@ -148,7 +148,7 @@ py.test is a no-boilerplate alternative to Python's standard unittest module.
Despite being a fully-featured and extensible test tool, it boasts a simple
syntax. Creating a test suite is as easy as writing a module with a couple of
functions
functions:
.. code-block:: python
@@ -251,9 +251,10 @@ the need to change any other code.
mock
----
mock is a library for testing in Python. Starting with Python 3.3, it is
available in the `standard library <http://docs.python.org/dev/library/unittest.mock`_. For older versions of
python, simply:
``mock`` is a library for testing in Python. As of Python 3.3, it is
available in the `standard library <http://docs.python.org/dev/library/unittest.mock`_.
For older versions of Python:
.. code-block:: console
@@ -262,7 +263,7 @@ python, simply:
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
For example, you can monkey-patch a method:
.. code-block:: python