you're reading...

Python Coding Style and Glossary

Python is a language that uses style in its construction and execution.

Indentation Levels
The indentation level in the source code is used to interpret the code. Since indentation also provides useful visual indicators of the program flow to human readers it plays a large role governing the construction of code and the control of execution. It is also the source of many bugs, and should be carefully considered when programming. It is standard practice to use exactly 4 spaces per indentation level.

Important Style Recommendations
Whitespace Usage
Use 4 spaces per indentation level.
Add 1 space after “,” in dicts, lists, tuples, and argument lists
Add 1 space after “:” in dicts, but not before.
Add 1 space around assignments and comparisons.
Add 1 blank line between function

No hard tabs.
Never mix tabs and spaces.
No spaces just inside parentheses or just before argument lists.
No spaces just inside docstrings.

Here is an example of good style in a function definition.

def make_iterable(key, value):
    """Return a tuple, list, and dictionary with one key, value pair. """
    t = (key, value)
    l = [key, value]
    d = {key: value}
    return t, l, d

In Python, a “name” or “identifier” is like a nametag attached to an object.

a = 1
a = 2

Here, an integer 1 object has a tag labelled “a”, and then we reassign the nametag “a” to another integer object:

 a = b 

If we assign one name to another, we’re just attaching the nametag “a” to an existing object tagged by “b”.

It is generally better to use longer and more descriptive names.
Coding Style for Names

lower case and joined “joined_lower” or “camelCase” for functions
lower case and joined “joined_lower” or “ALL_CAPS” for constants

Style for Compound Statements
Compound statements should be consistently aligned on separate lines.

food = 'spam'
if food == 'spam':
    print('Ummmm, my favorite!')
    print('I feel like saying it 100 times...')
    print(100 * (food + '! '))

Rely on For and Avoid While Loops to Iterate

As mentioned, Python is designed to use for loops to iterate across iterable objeccts, surprised?


i = 0
while i<len(lst):
    i += 1


for item in lst:

Sorting A Collection of Items With My_Keys

Tuples, Lists and Dictionaries that you would like to sort based on a key of progammer’s method, called “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])


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:

list_of_str =[ 'Zebra', 'snail', 'Barnacle']
list_of_str.sort() # ['Barnacle', 'Zebra', 'snail']
list_of_str.sort(key=str.lower) # ['Barnacle', 'snail', 'Zebra'] and will sort alphabetically regardless of case.


List Comprehensions

List comprehensions (“listcomps” for short) are syntax shortcuts for this general pattern:

[f(x) for x in S if P(x)] 

This produces a list containing the values of the sequence S selected by the predicate P and mapped by the function f. The if-clause is optional, and multiple for-clauses may be present

The traditional way is to do this with for and if statements:

new_list = []
for item in a_list:
    if condition(item):

# As a list comprehension:

new_list = [fn(item) for item in a_list
            if condition(item)]

Listcomps can be clearand concise, but should not be overused.

[n ** 2 for n in range(5)] # returns [0, 1, 4, 9, 16] a list of the squares of odd 0–4:
['spam!'+ str((n*(n-1))/2) for n in range(2,10) if n % 2] # returns list  ['spam!3', 'spam!10', 'spam!21', 'spam!36']

Docstring are used explain how to use code, and are for the users of your code. The main purpose of one is to explain the purpose of the function (as it might not be obvious to someone else later on) and to describe the arguments expected and the return values. Docstrings are useful in interactive use (help()) and for auto-documentation systems.

Arguments vs Parameters:
Parameters are the variables in the function definition and arguments are the values given to the variables at the point of function call. So outside the function, it is more common to talk about arguments to the function. Inside the function, you can really talk about either without ambiguity.

There are two kinds of arguments:
keyword argument: is an argument preceded by an identifier (e.g. name=) in a function call or passed as a value in a dictionary preceded by **. For example, 3 and 5 are both keyword arguments in the following calls to complex():

complex(real=3, imag=5)
complex(**{'real': 3, 'imag': 5})

positional argument: is an argument that is not a keyword argument. Positional arguments can appear at the beginning of an argument list and/or be passed as elements of an iterable preceded by *. For example, 3 and 5 are both positional arguments in the following calls:

complex(3, 5)
complex(*(3, 5))

Arguments are assigned to the named local variables in a function body.
Default Argument Values
A function can specify default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
    while True:
        ok = raw_input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise IOError('refusenik user')
        print complaint

Identifiers, Keywords, and Literals:
An identifier is defined as a sequence of one or more letters, digits and underscores, not starting with a digit. (This is Python’s definition, but many languages, like C or Java, use the same or a very similar definition.)

A keyword (or reserved word) is something that looks like an identifier in the language, but from the parser’s point of view acts like a token of the language.  Keywords cannot be used to name a variable (or function, class, etc.). Some well-known keywords in Python include ‘if’, ‘while’, ‘for’, ‘and’, ‘or’.

A literal is an element of an expression that describes a constant value. Examples of literals are numbers (e.g. 42, 3.14, or 1.6e-10) and strings (e.g. “Hello, world”). Literals are recognized by the parser, and the exact rules for how literals are parsed are often quite subtle.

Iterables and iterators
An iterable is an object capable of returning its members one at a time, and usable in for loops. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like dict and file. An iterator is a specific object constructed from an iterable, representing a stream of data.

First-class objects: all objects that can be named in Python (e.g., integers, floats, strings, lists, tuples, dicts, functions, classes, modules, methods, etc.) have equal status in that they can be assigned to variables, placed in lists, stored in dictionaries, passed as arguments, and so forth.

True/False/None: These are special literals that are also (now) keywords. True, False, and None are reserved words for special singleton objects (meaning there is only one of each). None  is used in many places in the language and library to represent the absence of some other value. For example, if d is a dictionary, d.get(k) will return d[k] if it exists, but None if d has no key k.



No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: