04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 10 ■ BATTERIES INCLUDED 213<br />

>>> help(copy.copy)<br />

Help on function copy in module copy:<br />

copy(x)<br />

Shallow copy operation on arbitrary Python objects.<br />

>>><br />

See the module's __doc__ string for more info.<br />

This is interesting: it tells you that copy takes a single argument x, and that it is a “shallow<br />

copy operation.” But it also mentions the module’s __doc__ string. What’s that? You may<br />

remember that I mentioned docstrings in Chapter 6. A docstring is simply a string you write at<br />

the beginning of a function to document it. That string is then stored in the function attribute<br />

__doc__. As you may understand from the preceding help text, modules may also have docstrings<br />

(they are written at the beginning of the module), as may classes (they are written at the beginning<br />

of the class).<br />

Actually, the preceding help text was extracted from the copy function’s docstring:<br />

>>> print copy.copy.__doc__<br />

Shallow copy operation on arbitrary Python objects.<br />

See the module's __doc__ string for more info.<br />

The advantage of using help over just examining the docstring directly like this is that you<br />

get more info, such as the function signature (that is, what arguments it takes). Try to call<br />

help(copy) (on the module itself) and see what you get. It prints out a lot of information, including<br />

a thorough discussion of the difference between copy and deepcopy (essentially that deepcopy(x)<br />

makes copies of the values stored in x as attributes and so on, while copy(x) just copies x, binding<br />

the attributes of the copy to the same values as those of x).<br />

Documentation<br />

A natural source for information about a module is, of course, its documentation. I’ve postponed<br />

the discussion of documentation because it’s often much quicker to just examine the module<br />

a bit yourself first. For example, you may wonder, “What were the arguments to range again?”<br />

Instead of searching through a Python book or the standard Python documentation for a<br />

description of range, you can just check it directly:<br />

>>> print range.__doc__<br />

range([start,] stop[, step]) -> list of integers<br />

Return a list containing an arithmetic progression of integers.<br />

range(i, j) returns [i, i+1, i+2,..., j-1]; start (!) defaults to 0.<br />

When step is given, it specifies the increment (or decrement).<br />

For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!<br />

These are exactly the valid indices for a list of 4 elements.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!