This link has been bookmarked by 739 people . It was first bookmarked on 26 Jul 2007, by ciukes ..
-
25 Jan 18
-
. (When an object has no more references or tags, it is removed from memory.)
-
-
22 Jan 18
Jason BlumIn this interactive tutorial, we'll cover many essential Python idioms and techniques in depth, adding immediately useful tools to your belt.
-
09 Jan 18
-
18 Jun 17
kevinoempty
-
15 Jun 17
-
12 Jun 17
-
06 Jun 17
-
27 May 17
-
10 May 17
-
21 Apr 17
-
One blank line between functions.
-
Two blank lines between classes.
-
- Add a space after "," in dicts, lists, tuples, & argument lists, and after ":" in dicts, but not before.
- Put spaces around assignments & comparisons (except in argument lists).
- No spaces just inside parentheses or just before argument lists.
- No spaces just inside docstrings.
-
joined_lower for functions, methods, attributes
joined_lower or ALL_CAPS for constants
StudlyCaps for classes
camelCase only to conform to pre-existing conventions
Attributes: interface, _internal, __private
But try to avoid the __private form. I never use it. Trust me. If you use it, you WILL regret it later.
-
Use backslashes as a last resort:
VeryLong.left_hand_side \ = even_longer.right_hand_side()
Backslashes are fragile; they must end the line they're on. If you add a space after the backslash, it won't work any more. Also, they're ugly. -
# !!! BUG: ... # !!! FIX: This is a hack # ??? Why is this here?
-
Both of these groups include you, so write good docstrings and comments!
Docstrings are useful in interactive use (help()) and for auto-documentation systems.
False comments & docstrings are worse than none at all. So keep them up to date! When you make changes, make sure the comments & docstrings are consistent with the code, and don't contradict it.
-
b, a = a, b
-
The right-hand side is unpacked into the names in the tuple on the left-hand side.
Further examples of unpacking:
>>> l =['David', 'Pythonista', '+1-514-555-1234'] >>> name, title, phone = l >>> name 'David' >>> title 'Pythonista' >>> phone '+1-514-555-1234'
-
The Python interpreter shows the parentheses for clarity, and I recommend you use parentheses too:
>>> (1,) (1,)
-
n the interactive interpreter, whenever you evaluate an expression or call a function, the result is bound to a temporary name, _ (an underscore):
>>> 1 + 1 2 >>> _ 2
_ stores the last printed expressio
-
Don't do this:
result = '' for s in colors: result += s
This is very inefficient.
It has terrible memory usage and performance patterns. The "summation" will compute, store, and then throw away each intermediate step.
Instead, do this:
result = ''.join(colors)
The join() string method does all the copying in one pass.
-
olors = ['red', 'blue', 'green', 'yellow'] print 'Choose', ', '.join(colors[:-1]), \ 'or', colors[-1]
-
The "slice until -1" ([:-1]) gives all but the last value, which we join with comma-space.
-
result = ''.join(fn(i) for i in items)
-
for key in d.keys(): d[str(key)] = d[key]
-
# do this: if key in d: ...do something with d[key] # not this: if d.has_key(key): ...do something with d[key]
-
This is the naïve way to do it:
navs = {} for (portfolio, equity, position) in data: if portfolio not in navs: navs[portfolio] = 0 navs[portfolio] += position * prices[equity]dict.get(key, default) removes the need for the test:
navs = {} for (portfolio, equity, position) in data: navs[portfolio] = (navs.get(portfolio, 0) + position * prices[equity])Much more direct. -
Initializing mutable dictionary values:
equities = {} for (portfolio, equity) in data: if portfolio in equities: equities[portfolio].append(equity) else: equities[portfolio] = [equity]dict.setdefault(key, default) does the job much more efficiently:
equities = {} for (portfolio, equity) in data: equities.setdefault(portfolio, []).append( equity) -
dict.setdefault() is equivalent to "get, or set & get". Or "set if necessary, then get". It's especially efficient if your dictionary key is expensive to compute or long to type.
The only problem with dict.setdefault() is that the default value is always evaluated, whether needed or not. That only matters if the default value is expensive to compute.
If the default value is expensive to compute, you may want to use the defaultdict class, which we'll cover shortly.
-
# do this: # not this: if x: if x == True: pass pass
It's elegant and efficient to take advantage of the intrinsic truth values (or Boolean values) of Python objects.Testing a list:
# do this: # not this: if items: if len(items) != 0: pass pass # and definitely not this: if items != []: pass
-
ss MyContainer(object): def __init__(self, data): self.data = data def __len__(self): """Return my length.""" return len(self.data)
If your class is not a container, use __nonzero__:
class MyClass(object): def __init__(self, value): self.value = value def __nonzero__(self): """Return my truth value (True or False).""" # This could be arbitrarily complex: return bool(self.value)
In Python 3.0, __nonzero__ has been renamed to __bool__ for consistency with the bool built-in type. For compatibility, add this to the class definition:
__bool__ = __nonzero__
-
>>> print list(enumerate(items)) [(0, 'zero'), (1, 'one'), (2, 'two'), (3, 'three')]
-
for (index, item) in enumerate(items): print index, item
-
Python has "names"
In Python, a "name" or "identifier" is like a parcel tag (or nametag) attached to an object.a = 1
Here, an integer 1 object has a tag labelled "a".
If we reassign to "a", we just move the tag to another object:
a = 2
Now the name "a" is attached to an integer 2 object.
The original integer 1 object no longer has a tag "a". It may live on, but we can't get to it through the name "a". (When an object has no more references or tags, it is removed from memory.)
If we assign one name to another, we're just attaching another nametag to an existing object:
b = a
The name "b" is just a second tag bound to the same object as "a".Although we commonly refer to "variables" even in Python (because it's common terminology), we really mean "names" or "identifiers". In Python, "variables" are nametags for values, not labelled boxes.
-
-
22 Mar 17
-
06 Jan 17
-
19 Dec 16
-
24 Oct 16
-
06 Sep 16
-
07 Jul 16
dnazarovBut try to avoid the __private form. I never use it. Trust me. If you use it, you WILL regret it later. People coming from a C++/Java background are especially prone to overusing/misusing this "feature". But __private names don't work the same way a…
-
06 Jul 16
-
22 May 16
-
17 May 16
-
12 Mar 16
-
03 Feb 16
-
26 Jan 16
-
04 Jan 16
-
- The comma is the tuple constructor syntax.
- A tuple is created on the right (tuple packing).
- A tuple is the target on the left (tuple unpacking).
-
-
03 Jan 16
-
30 Dec 15
Frederico MaranhãoBut try to avoid the __private form. I never use it. Trust me. If you use it, you WILL regret it later. People coming from a C++/Java background are especially prone to overusing/misusing this "feature". But __private names don't work the same way a…
-
23 Oct 15
-
19 Oct 15
-
13 Aug 15
-
28 Jun 15
-
17 Jun 15
-
03 Jun 15
-
22 May 15
-
28 Apr 15
-
13 Feb 15
-
PEP = Python Enhancement Proposal
-
IDLE and the Emacs Python mode
-
camelCase only to conform to pre-existing conventions
-
interface, _internal
-
avoid the __private form. I never use it. Trust me. If you use it, you WILL regret it later
-
implied line continuation
-
backslashes as a last resort
-
Comments = Why (rationale) & how code works
-
b, a = a, b
-
tuple constructor
-
tuple packing
-
tuple unpacking
-
unpacked
-
_ stores the last printed expression.
-
interactive interpreter
-
Don't do this:
result = '' for s in colors: result += s
-
result = ''.join(colors)
-
colors[:-1]
-
corner cases
-
''.join(fn(i) for i in items)
-
generator expression
-
also works for items in arbitrary containers (such as lists, tuples, and sets)
-
mutating the dictionary
-
static list
-
"RuntimeError: dictionary changed size during iteration"
-
if key in d:
-
removes the need for the test
-
dict.get(key, default)
-
navs.get(portfolio, 0)
-
if portfolio in equities: equities[portfolio].append(equity) else: equities[portfolio] = [equity]
-
equities.setdefault(portfolio, []).append( equity)
-
navs.setdefault(portfolio, 0)
-
sets the dictionary value only if there is no value already.
-
True (== 1)
-
False (== 0)
-
container
-
__nonzero__
-
__len__
-
__len__
-
len(self.data)
-
not a container
-
__nonzero__
-
bool(self.value)
-
(index, item) pairs
-
enumerate(items)
-
range(len(items))
-
iterator
-
generator
-
iterator
-
enumerate(items)
-
e.next()
-
Box "a"
-
"name" or "identifier"
-
a parcel tag (or nametag)
-
we're just attaching another nametag to an existing object
-
a second tag
-
"names" or "identifiers"
-
labelled boxes
-
nametags for values
-
evaluated at function definition time
-
create it at run time
-
Lists are a mutable objects
-
a_list = []
-
%(name)s
-
%(messages)i
-
values
-
local namespace
-
locals()
-
locally-available names
-
from pprint import pprint
-
debugging your data structures much easier
-
pprint
-
an object's instance attributes
-
a dictionary, self.__dict__
-
namespace
-
"We found %(error_count)d errors" % self.__dict__
-
chained dictionary lookups
-
class __dict__
-
Namespace lookups
-
traditional way
-
a list comprehension
-
[fn(item) for item in a_list if condition(item)]
-
Listcomps
-
[n ** 2 for n in range(10)]
-
[n ** 2 for n in range(10) if n % 2]
-
generator expression
-
num * num for num in xrange(1, 101)
-
generator expressions are lazy
-
listcomps are greedy
-
useful for long sequences
-
use xrange for the same reason: it lazily produces values
-
generator expressions don't.
-
listcomps have square brackets
-
Generator expressions sometimes do require enclosing parentheses though, so you should always use them.
-
list comprehension
-
intermediate step
-
generator expression
-
a_list.sort(custom_cmp)
-
to_sort.sort(key=my_key)
-
yield
-
yield
-
next method
-
StopIteration exception
-
for loops just call the next method
-
don't need to build concrete lists
-
datafile = open('datafile') for line in datafile: do_something(line)
-
files support a next method
-
EAFP vs. LBYL
-
It's easier to ask forgiveness than permission
-
Look before you leap
-
If x must be a string for your code to work, why not call
str(x)
instead of trying something like
isinstance(x, str)
-
you try to read six months from now
-
The from module import * wild-card style leads to namespace pollution.
-
local namespace
-
won't be able to figure out where certain names come from
-
production code
-
Instead
-
top-level
-
major executable code
-
functions, classes, methods
-
Module Structure
-
constants
-
exception classes
-
interface functions
-
classes
-
internal functions & classes
-
#!/usr/bin/env python
-
""" Module docstring. """
-
sys.argv[1:]
-
process_command_line(argv)
-
settings, args
-
package
-
module1
-
subpackage
-
module2
-
load-path
-
absolute and relative imports
-
not smart enough to debug it
-
if you write the code as cleverly as possible
-
keep your programs simple
-
Python's standard library
-
Python Package Index
-
"Cheese Shop"
-
http://cheeseshop.python.org/pypi
-
Search the web. Google is your friend.
-
-
03 Dec 14
-
23 Nov 14
-
- The comma is the tuple constructor syntax.
- A tuple is created on the right (tuple packing).
- A tuple is the target on the left (tuple unpacking).
Perhaps you've seen this before. But do you know how it works?
-
-
27 Sep 14
mhotanEffective Python
-
22 Sep 14
-
30 Aug 14
-
21 Jul 14
-
19 Jul 14
-
15 Jul 14
-
03 Jul 14
-
27 Jun 14
-
24 Jun 14
-
23 Jun 14
-
19 Jun 14
-
12 Jun 14
-
29 May 14
-
27 May 14
-
20 May 14
-
06 Mar 14
Young Lee"Code Like a Pythonista: Idiomatic Python" http://t.co/bjL30xWEpS 파이썬 코딩 스타일
-
27 Feb 14
-
One blank line between functions.
-
Two blank lines between classes.
-
joined_lower for functions, methods, attributes
-
joined_lower or ALL_CAPS for constants
-
StudlyCaps for classes
-
camelCase only to conform to pre-existing conventions
-
But try to avoid the __private form. I never use it. Trust me. If you use it, you WILL regret it later.
-
It's better to use the single-leading-underscore convention, _internal. This isn't name mangled at all; it just indicates to others to "be careful with this, it's an internal implementation detail; don't touch it if you don't fully understand it". It's only a convention though.
-
Use backslashes as a last resort:
VeryLong.left_hand_side \ = even_longer.right_hand_side()
Backslashes are fragile; they must end the line they're on. If you add a space after the backslash, it won't work any more. Also, they're ugly. -
The string prefixed with an "r" is a "raw" string. Backslashes are not evaluated as escapes in raw strings. They're useful for regular expressions and Windows filesystem paths.
-
That's because this automatic concatenation is a feature of the Python parser/compiler, not the interpreter. You must use the "+" operator to concatenate strings at run time.
-
'''\ Triple single quotes\ '''
-
Docstrings & Comments
-
work our way up
-
dict.get(key, default) removes the need for the test:
-
dict.setdefault() is equivalent to "get, or set & get". Or "set if necessary, then get". It's especially efficient if your dictionary key is expensive to compute or long to type.
The only problem with dict.setdefault() is that the default value is always evaluated, whether needed or not. That only matters if the default value is expensive to compute.
If the default value is expensive to compute, you may want to use the defaultdict class, which we'll cover shortly.
-
You should be careful with defaultdict though. You cannot get KeyError exceptions from properly initialized defaultdict instances. You have to use a "key in dict" conditional if you need to check for the existence of a specific key.
-
However, the order is guaranteed to be consistent (in other words, the order of keys will correspond to the order of values), as long as the dictionary isn't changed between calls.
-
In Python 3.0, __nonzero__ has been renamed to __bool__ for consistency with the bool built-in type. For compatibility, add this to the class definition:
__bool__ = __nonzero__
-
enumerate is a lazy function
-
"%s" is particularly useful because it uses Python's built-in str() function to to convert any object to a string.
-
"%i" means "convert an integer to a string and insert here"
-
values = {'name': name, 'messages': messages} print ('Hello %(name)s, you have %(messages)i ' 'messages' % values)
-
- Use a list comprehension when a computed list is the desired end result.
- Use a generator expression when the computed list is just an intermediate step.
Rule of thumb:
-
- The dict() built-in takes a list of key/value pairs (2-tuples).
- We have a list of month codes (each month code is a single letter, and a string is also just a list of letters). We enumerate over this list to get both the month code and the index.
- The month numbers start at 1, but Python starts indexing at 0, so the month number is one more than the index.
- We want to look up months both as strings and as integers. We can use the int() and str() functions to do this for us, and loop over them.
Here's a recent example I saw at work.
➔We needed a dictionary mapping month numbers (both as string and as integers) to month codes for futures contracts. It can be done in one logical line of code.
➔The way this works is as follows:
Recent example:
month_codes = dict((fn(i+1), code) for i, code in enumerate('FGHJKMNQUVXZ') for fn in (int, str))month_codes result:
{ 1: 'F', 2: 'G', 3: 'H', 4: 'J', ... '1': 'F', '2': 'G', '3': 'H', '4': 'J', ...} -
Sorting
It's easy to sort a list in Python:a_list.sort()
(Note that the list is sorted in-place: the original list is sorted, and the sort method does not return the list or a copy.)
But what if you have a list of data that you need to sort, but it doesn't sort naturally (i.e., sort on the first column, then the second column, etc.)? You may need to sort on the second column first, then the fourth column.
We can use list's built-in sort method with a custom function:
def custom_cmp(item1, item2): return cmp((item1[1], item1[3]), (item2[1], item2[3])) a_list.sort(custom_cmp)
This works, but it's extremely slow for large lists. -
This is a tradeoff of space and complexity against time. Much simpler and faster, but we do need to duplicate the original list.
-
Sorting With Keys
Python 2.4 introduced an optional argument to the sort list method, "key", which specifies a function of one argument that is used to compute a comparison key from each list element. For example:def my_key(item): return (item[1], item[3]) to_sort.sort(key=my_key)
The function my_key will be called once for each item in the to_sort list.
You can make your own key function, or use any existing one-argument function if applicable:
- str.lower to sort alphabetically regarless of case.
- len to sort on the length of the items (strings or containers).
- int or float to sort numerically, as with numeric strings like "2", "123", "35".
-
This is how a for loop really works. Python looks at the sequence supplied after the in keyword. If it's a simple container (such as a list, tuple, dictionary, set, or user-defined container) Python converts it into an iterator. If it's already an iterator, Python uses it directly.
-
A for loop can have an else clause, whose code is executed after the iterator runs dry, but not after a break statement is executed. This distinction allows for some elegant uses. else clauses are not always or often used on for loops, but they can come in handy. Sometimes an else clause perfectly expresses the logic you need
-
There is a caveat here: because of the way the buffering is done, you cannot mix .next & .read* methods unless you're using Python 2.5+.
-
Exceptions
Use coercion if an object must be a particular type. If x must be a string for your code to work, why not call
str(x)
instead of trying something like
isinstance(x, str)
-
Note: Always specify the exceptions to catch. Never use bare except clauses. Bare except clauses will catch unexpected exceptions, making your code exceedingly difficult to debug.
-
Although a convenient shortcut, this should not be in production code.
-
Note that this form doesn't lend itself to use in the interactive interpreter, where you may want to edit and "reload()" a module.
-
Except for special cases, you shouldn't put any major executable code at the top-level. Put code in functions, classes, methods, and guard it with if __name__ == '__main__'.
-
Module Structure
"""module docstring""" # imports # constants # exception classes # interface functions # classes # internal functions & classes def main(...): ... if __name__ == '__main__': status = main() sys.exit(status)
-
package/ __init__.py module1.py subpackage/ __init__.py module2.py
- Used to organize your project.
- Reduces entries in load-path.
- Reduces import name conflicts.
Example:
import package.module1 from package.subpackage import module2 from package.subpackage.module2 import name
In Python 2.5 we now have absolute and relative imports via a future import:
from __future__ import absolute_import
I haven't delved into these myself yet, so we'll conveniently cut this discussion short.
-
-
15 Feb 14
-
31 Jan 14
-
10 Jan 14
-
27 Dec 13
-
23 Dec 13
Vivek ViswanathanReally good coding style start to programming in python
-
People coming from a C++/Java background are especially prone to overusing/misusing this "feature". But __private names don't work the same way as in Java or C++. They just trigger a name mangling whose purpose is to prevent accidental namespace collisions in subclasses: MyClass.__private just becomes MyClass._MyClass__private. (Note that even this breaks down for subclasses with the same name as the superclass, e.g. subclasses in different modules.) It is possible to access __private names from outside their class, just inconvenient and fragile (it adds a dependency on the exact name of the superclass).
The problem is that the author of a class may legitimately think "this attribute/method name should be private, only accessible from within this class definition" and use the __private convention. But later on, a user of that class may make a subclass that legitimately needs access to that name. So either the superclass has to be modified (which may be difficult or impossible), or the subclass code has to use manually mangled names (which is ugly and fragile at best).
-
-
09 Dec 13
-
06 Dec 13
-
It's better to use the single-leading-underscore convention, _internal. This isn't name mangled at all; it just indicates to others to "be careful with this, it's an internal implementation detail; don't touch it if you don't fully understand it". It's only a convention though.
-
"r" is a "raw" string. Backslashes are not evaluated as escapes in raw strings.
-
It has terrible memory usage and performance patterns. The "summation" will compute, store, and then throw away each intermediate step.
-
join() string method does all the copying in one pass.
-
This is a common mistake that beginners often make. Even more advanced programmers make this mistake if they don't understand Python names.
def bad_append(new_item, a_list=[]): a_list.append(new_item) return a_list
The problem here is that the default value of a_list, an empty list, is evaluated at function definition time. So every time you call the function, you get the same default value. Try it several times:>>> print bad_append('one') ['one']>>> print bad_append('two') ['one', 'two'] -
The correct way to get a default list (or dictionary, or set) is to create it at run time instead, inside the function:
-
ython's built-in str() function to to convert any object to a string
-
namespace of an object's instance attributes is just a dictionary, self.__dict__.
-
new_list = [fn(item) for item in a_list if condition(item)]
-
Listcomps are clear & concise, up to a point
-
use the sum function to quickly do the work for us, by building the appropriate sequence.
-
As a list comprehension:
total = sum([num * num for num in range(1, 101)])
As a generator expression:
total = sum(num * num for num in xrange(1, 101))
-
Generator expressions compute one value at a time, when needed, as individual values. This is especially useful for long sequences where the computed list is just an intermediate step and not the final result.
-
to_sort.sort(key=my_key)
-
yield value
-
When you call a generator function, instead of running the code immediately Python returns a generator object, which is an iterator; it has a next method. for loops just call the next method on the iterator, until a StopIteration exception is raised. You can raise StopIteration explicitly, or implicitly by falling off the end of the generator code as above.
-
else clauses are not always or often used on for loops, but they can come in handy. Sometimes an else clause perfectly expresses the logic you need.
-
Generally EAFP is preferred, but not always.
-
Use coercion if an object must be a particular type. If x must be a string for your code to work, why not call
-
wrap exception-prone code in a try/except
-
Never use bare except clauses. Bare except clauses will catch unexpected exceptions, making your code exceedingly difficult to debug
-
When imported, a module's __name__ attribute is set to the module's file name, without ".py". So the code guarded by the if statement above will not run when imported.
-
-
31 Oct 13
-
25 Oct 13
-
05 Oct 13
-
24 Sep 13
-
02 Sep 13
-
19 Aug 13
-
13 Aug 13
-
07 Aug 13
-
28 Jul 13
-
08 Jul 13
-
29 Jun 13
-
25 May 13
-
08 Apr 13
-
17 Mar 13
-
04 Mar 13
-
01 Mar 13
-
26 Feb 13
-
20 Feb 13
-
05 Jan 13
-
01 Jan 13
-
18 Dec 12
-
06 Dec 12
-
10 Oct 12
-
03 Oct 12
-
13 Sep 12
-
10 Sep 12
-
06 Sep 12
-
01 Sep 12
-
StudlyCaps for classes
camelCase only to conform to pre-existing conventions
-
Attributes: interface, _internal, __private
But try to avoid the __private form. I never use it. Trust me. If you use it, you WILL regret it later.
-
There's a concept in Python: "we're all consenting adults here".
-
It's better to use the single-leading-underscore convention, _internal. This isn't name mangled at all; it just indicates to others to "be careful with this, it's an internal implementation detail; don't touch it if you don't fully understand it". It's only a convention though.
-
Use implied line continuation inside parentheses/brackets/braces
-
Use backslashes as a last resort
-
The string prefixed with an "r" is a "raw" string. Backslashes are not evaluated as escapes in raw strings. They're useful for regular expressions and Windows filesystem paths.
-
Docstrings = How to use code
-
Comments = Why (rationale) & how code works
-
False comments & docstrings are worse than none at all. So keep them up to date! When you make changes, make sure the comments & docstrings are consistent with the code, and don't contradict it.
-
In the interactive interpreter, whenever you evaluate an expression or call a function, the result is bound to a temporary name, _ (an underscore)
-
We often have to initialize dictionary entries before use:
This is the naïve way to do it:navs = {} for (portfolio, equity, position) in data: if portfolio not in navs: navs[portfolio] = 0 navs[portfolio] += position * prices[equity]dict.get(key, default) removes the need for the test:
navs = {} for (portfolio, equity, position) in data: navs[portfolio] = (navs.get(portfolio, 0) + position * prices[equity])Much more direct. -
- it takes an extra first argument: a default factory function; and
- when a dictionary key is encountered for the first time, the default factory function is called and the result used to initialize the dictionary value.
defaultdict
New in Python 2.5.
defaultdict is new in Python 2.5, part of the collections module. defaultdict is identical to regular dictionaries, except for two things:
-
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
—Brian W. Kernighan, co-author of The C Programming Language and the "K" in "AWK"
-
-
30 Aug 12
-
19 Aug 12
-
16 Aug 12
-
15 Aug 12
-
13 Aug 12
-
-
Add a space after "," in dicts, lists, tuples, & argument lists, and after ":" in dicts, but not before.
-
But try to avoid the __private form. I never use it. Trust me. If you use it, you WILL regret it later.
-
But __private names don't work the same way as in Java or C++. They just trigger a name mangling whose purpose is to prevent accidental namespace collisions in subclasses: MyClass.__private just becomes MyClass._MyClass__private. (Note that even this breaks down for subclasses with the same name as the superclass, e.g. subclasses in different modules.) It is possible to access __private names from outside their class, just inconvenient and fragile (it adds a dependency on the exact name of the superclass).
-
It's better to use the single-leading-underscore convention, _internal. This isn't name mangled at all; it just indicates to others to "be careful with this, it's an internal implementation detail; don't touch it if you don't fully understand it". It's only a convention though.
-
backslashes as a last resort:
-
spaces between literals are not required, but help with readability
-
Note named string objects are not concatenated:
-
Whitespace & indentations are useful visual indicators of the program flow
-
Multiple statements on one line are a cardinal sin. In Python, readability counts.
-
Docstrings explain how to use code, and are for the users of your code
-
Comments explain why, and are for the maintainers of your code.
-
False comments & docstrings are worse than none at all. So keep them up to date!
-
is unpacke
-
the comma is the tuple constructor, not the parentheses
-
The Python interpreter shows the parentheses for clarity, and I recommend you use parentheses too
-
Don't forget the comma!
>>> (1) 1
-
_ stores the last printed expression.
-
But get in the habit of building strings efficiently, because with thousands or with loops, it will make a difference.
-
Use in where possible (1)
-
.keys() is necessary when mutating the dictionary
-
dict.get(key, default) removes the need for the test:
-
dict.setdefault(key, default) does the job much more efficiently:
-
dict.setdefault() is equivalent to "get, or set & get". Or "set if necessary, then get".
-
If the default value is expensive to compute, you may want to use the defaultdict class
-
You should be careful with defaultdict though. You cannot get KeyError exceptions from properly initialized defaultdict instances. You have to use a "key in dict" conditional if you need to check for the existence of a specific key.
-
zip(given, family)
-
.split()
-
n Python, a "name" or "identifier" is like a parcel tag (or nametag) attached to an object.
-
Although we commonly refer to "variables" even in Python (because it's common terminology), we really mean "names" or "identifiers". In Python, "variables" are nametags for values, not labelled boxes.
-
default value of a_list, an empty list, is evaluated at function definition time. So every time you call the function, you get the same default value
-
The correct way to get a default list (or dictionary, or set) is to create it at run time instead, inside the function:
-
Python's % operator works like C's sprintf function.
-
As a generator expression:
total = sum(num * num for num in xrange(1, 101))
-
except that where listcomps are greedy, generator expressions are lazy
-
especially useful for long sequences where the computed list is just an intermediate step and not the final result
-
- Use a list comprehension when a computed list is the desired end result.
- Use a generator expression when the computed list is just an intermediate step.
-
yield value value += 1
-
hen you call a generator function, instead of running the code immediately Python returns a generator object, which is an iterator; it has a next method. for loops just call the next method on the iterator, until a StopIteration exception is raised
-
Use coercion if an object must be a particular type. If x must be a string for your code to work, why not call
str(x)
instead of trying something like
isinstance(x, str)
-
To make a simultaneously importable module and executable script:
if __name__ == '__main__': # script code here
When imported, a module's __name__ attribute is set to the module's file name, without ".py". So the code guarded by the if statement above will not run when imported. When executed as a script though, the __name__ attribute is set to "__main__", and the script code will run.
-
Module Structure
"""module docstring""" # imports # constants # exception classes # interface functions # classes # internal functions & classes def main(...): ... if __name__ == '__main__': status = main() sys.exit(status)
This is how a module should be structured. -
import optparse
-
-
10 Aug 12
-
04 Aug 12
-
PEP = Python Enhancement Proposal
-
"r" is a "raw" string
-
That's because this automatic concatenation is a feature of the Python parser/compiler, not the interpreter.
-
-
02 Aug 12
Page Comments
Would you like to comment?
Join Diigo for a free account, or sign in if you are already a member.