mirror of
https://github.com/kennethreitz/python-guide.git
synced 2026-06-05 23:00:18 +00:00
@@ -69,7 +69,7 @@ PyPy aims for maximum compatibility with the reference CPython implementation
|
|||||||
while improving performance.
|
while improving performance.
|
||||||
|
|
||||||
If you are looking to squeeze more performance out of your Python code, it's
|
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 <http://speed.pypy.org/>`_.
|
faster than CPython <http://speed.pypy.org/>`_.
|
||||||
|
|
||||||
Currently PyPy supports Python 2.7. [#pypy_ver]_
|
Currently PyPy supports Python 2.7. [#pypy_ver]_
|
||||||
@@ -90,11 +90,11 @@ Currently Jython supports up to Python 2.5. [#jython_ver]_
|
|||||||
IronPython
|
IronPython
|
||||||
----------
|
----------
|
||||||
|
|
||||||
`IronPython <http://ironpython.net/>`_ is an implementation of Python for .NET
|
`IronPython <http://ironpython.net/>`_ is an implementation of Python for the .NET
|
||||||
framework. It can use both Python and .NET framework libraries, and can also
|
framework. It can use both Python and .NET framework libraries, and can also
|
||||||
expose Python code to other .NET languages.
|
expose Python code to other .NET languages.
|
||||||
|
|
||||||
`Python Tools for Visual Studio <http://ironpython.net/tools/>`_ integrate
|
`Python Tools for Visual Studio <http://ironpython.net/tools/>`_ integrates
|
||||||
IronPython directly in to the Visual Studio development environment, making it
|
IronPython directly in to the Visual Studio development environment, making it
|
||||||
an ideal choice for Windows developers.
|
an ideal choice for Windows developers.
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
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 (?).
|
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.
|
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"
|
In this example python expects to find a "spam.py" file in a folder named "my"
|
||||||
@@ -281,7 +281,7 @@ Decorators
|
|||||||
----------
|
----------
|
||||||
|
|
||||||
The Python language provides a simple yet powerful syntax called '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
|
or a method. The 'decorated' function or method will replace the original
|
||||||
'undecorated' function or method. Because functions are first-class objects
|
'undecorated' function or method. Because functions are first-class objects
|
||||||
in Python, it can be done 'manually', but using the @decorator syntax is
|
in Python, it can be done 'manually', but using the @decorator syntax is
|
||||||
@@ -445,7 +445,8 @@ with calls to append().
|
|||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
# create a concatenated string from 0 to 19 (e.g. "012..1819")
|
# 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
|
One final thing to mention about strings is that using join() is not always
|
||||||
best. In the instances where you are creating a new string from a pre-determined
|
best. In the instances where you are creating a new string from a pre-determined
|
||||||
|
|||||||
+14
-14
@@ -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
|
One reason for Python code to be easily read and understood is its relatively
|
||||||
complete set of Code Style guidelines and "Pythonic" idioms.
|
complete set of Code Style guidelines and "Pythonic" idioms.
|
||||||
|
|
||||||
Moreover, when a veteran Python developer (a Pythonista) point to some
|
Moreover, when a veteran Python developer (a Pythonista) points to portions of code
|
||||||
parts of a code and say it is not "Pythonic", it usually means that these lines
|
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
|
of code do not follow the common guidelines and fail to express the intent in
|
||||||
what is considered the best (hear: most readable) way.
|
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
|
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
|
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
|
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.
|
arguments, and in which order.
|
||||||
|
|
||||||
In those two cases, it is possible to use argument names when calling the functions
|
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
|
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
|
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)``.
|
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.
|
passed another value.
|
||||||
|
|
||||||
Calling a function with keyword arguments can be done in multiple ways in Python,
|
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
|
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
|
properties and methods: there is no "private" keyword in Python. This
|
||||||
philosophy, very different from highly defensive languages like Java, which
|
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".
|
are consenting adults".
|
||||||
|
|
||||||
This doesn't mean that, for example, no properties are considered private, and
|
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
|
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
|
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.
|
elements should not be accessed directly.
|
||||||
|
|
||||||
The main convention for private properties and implementation details is to
|
The main convention for private properties and implementation details is to
|
||||||
prefix all "internals" with an underscore. If the client code breaks this rule
|
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.
|
the code is modified is the responsibility of the client code.
|
||||||
|
|
||||||
Using this convention generously is encouraged: any method or property that is
|
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
|
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
|
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
|
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
|
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
|
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
|
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
|
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.
|
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
|
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
|
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
|
point. This will also help factoring out some code paths, and the multiple exit points
|
||||||
is a probable indication that such a refactoring is needed.
|
are a probable indication that such a refactoring is needed.
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
@@ -351,7 +351,7 @@ Take the following code for example::
|
|||||||
return 's' in 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.
|
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 <http://stackoverflow.com/questions/513882/python-list-vs-dict-for-look-up-table>`_ page.
|
For more information see this `StackOverflow <http://stackoverflow.com/questions/513882/python-list-vs-dict-for-look-up-table>`_ page.
|
||||||
|
|
||||||
Zen of Python
|
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
|
added to the end of the line, after the backslash, will break the code and may
|
||||||
have unexpected results.
|
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
|
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.
|
and square braces.
|
||||||
|
|
||||||
**Bad**:
|
**Bad**:
|
||||||
|
|||||||
Reference in New Issue
Block a user