15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

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

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

3.4. Basic Style Guidelines<br />

Comments<br />

You do not need to be reminded that comments are useful both to you and those who come after you.<br />

This is especially true for code that has been untouched by man (or woman) for a time (that means<br />

several months in software development time). Comments should not be absent, nor should there be<br />

novellas. Keep the comments explanatory, clear, short, and concise, but get them in there. In the end,<br />

it saves time and energy for everyone. Above all, make sure they stay accurate!<br />

Documentation<br />

<strong>Python</strong> also provides a mechanism whereby documentation strings can be retrieved dynamically through<br />

the __doc__ special variable. The first unassigned string in a module, class declaration, or function<br />

declaration can be accessed using the attribute obj.__doc__ where obj is the module, class, or function<br />

name. This works during runtime too!<br />

Indentation<br />

Since indentation plays a major role, you will have to decide on a spacing style that is easy to read as<br />

well as the least confusing. Common sense also plays a role in choosing how many spaces or columns to<br />

indent.<br />

1 or 2 Probably not enough; difficult to determine which block of code statements belong to<br />

8 to 10 May be too many; code that has many embedded levels will wrap around, causing the source<br />

to be difficult to read<br />

Four spaces is very popular, not to mention being the preferred choice of <strong>Python</strong>'s creator. Five and six<br />

are not bad, but text editors usually do not use these settings, so they are not as commonly used. Three<br />

and seven are borderline cases.<br />

As far as tabs go, bear in mind that different text editors have different concepts of what tabs are. It is<br />

advised not to use tabs if your code will live and run on different systems or be accessed with different<br />

text editors.<br />

Choosing Identifier Names<br />

The concept of good judgment also applies in choosing logical identifier names. Decide on short yet<br />

meaningful identifiers for variables. Although variable length is no longer an issue with programming<br />

languages of today, it is still a good idea to keep name sizes reasonable length. The same applies for<br />

naming your modules (<strong>Python</strong> files).<br />

<strong>Python</strong> Style Guide(s)<br />

Guido van Rossum wrote up a <strong>Python</strong> Style Guide ages ago. It has since been replaced by no fewer than

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

Saved successfully!

Ooh no, something went wrong!